mstch/src/render_context.cpp

58 lines
1.7 KiB
C++
Raw Normal View History

2015-04-09 20:41:27 +02:00
#include "render_context.h"
#include "state/outside_section.h"
#include <regex>
using namespace mstch;
const mstch::node render_context::null_node;
2015-04-10 12:56:08 +02:00
render_context::render_context(
const mstch::object& object,
2015-04-10 12:56:08 +02:00
const std::map<std::string,std::string>& partials):
2015-04-09 20:41:27 +02:00
partials(partials),
objects{object},
2015-04-09 20:41:27 +02:00
state(new state::outside_section)
{
}
2015-04-10 12:56:08 +02:00
render_context::render_context(
const mstch::object& object,
const render_context& context):
partials(context.partials),
objects(context.objects),
state(new state::outside_section)
2015-04-09 20:41:27 +02:00
{
objects.push_front(object);
}
2015-04-10 12:56:08 +02:00
const mstch::node& render_context::find_node(
const std::string& token,
const std::deque<object>& current_objects)
2015-04-10 12:56:08 +02:00
{
2015-04-11 16:29:12 +02:00
if (token != "." && token.find('.') != std::string::npos)
2015-04-10 12:56:08 +02:00
return find_node(
token.substr(token.rfind('.') + 1),
{boost::get<object>(find_node(
token.substr(0, token.rfind('.')),
current_objects))});
2015-04-11 16:29:12 +02:00
else
2015-04-09 20:41:27 +02:00
for (auto& object: current_objects)
2015-04-11 16:29:12 +02:00
if (object.count(token))
2015-04-09 20:41:27 +02:00
return object.at(token);
2015-04-11 16:29:12 +02:00
return null_node;
2015-04-09 20:41:27 +02:00
}
const mstch::node& render_context::get_node(const std::string& token) {
return find_node(token, objects);
}
std::string render_context::render(const std::string& t) {
std::ostringstream output;
auto re = std::regex("\\{{2}[^\\}]*\\}{2}|\\{{3}[^\\}]*\\}{3}");
std::sregex_token_iterator it(t.begin(), t.end(), re, {-1, 0});
for (; it != std::sregex_token_iterator(); ++it)
2015-04-09 20:41:27 +02:00
output << state->render(*this, token(it->str()));
return output.str();
}