]> Creatis software - cpPlugins.git/blob - lib/mstch/render_context.cpp
Moved to version 1.0
[cpPlugins.git] / lib / mstch / render_context.cpp
1 #include "render_context.hpp"
2 #include "state/outside_section.hpp"
3 #include "visitor/get_token.hpp"
4
5 using namespace mstch;
6
7 const mstch::node render_context::null_node;
8
9 render_context::push::push(render_context& context, const mstch::node& node):
10     m_context(context)
11 {
12   context.m_nodes.emplace_front(node);
13   context.m_node_ptrs.emplace_front(&node);
14   context.m_state.push(std::unique_ptr<render_state>(new outside_section));
15 }
16
17 render_context::push::~push() {
18   m_context.m_nodes.pop_front();
19   m_context.m_node_ptrs.pop_front();
20   m_context.m_state.pop();
21 }
22
23 std::string render_context::push::render(const template_type& templt) {
24   return m_context.render(templt);
25 }
26
27 render_context::render_context(
28     const mstch::node& node,
29     const std::map<std::string, template_type>& partials):
30     m_partials(partials), m_nodes(1, node), m_node_ptrs(1, &node)
31 {
32   m_state.push(std::unique_ptr<render_state>(new outside_section));
33 }
34
35 const mstch::node& render_context::find_node(
36     const std::string& token,
37     std::list<node const*> current_nodes)
38 {
39   if (token != "." && token.find('.') != std::string::npos)
40     return find_node(token.substr(token.rfind('.') + 1),
41         {&find_node(token.substr(0, token.rfind('.')), current_nodes)});
42   else
43     for (auto& node: current_nodes)
44       if (visit(has_token(token), *node))
45         return visit(get_token(token, *node), *node);
46   return null_node;
47 }
48
49 const mstch::node& render_context::get_node(const std::string& token) {
50     return find_node(token, m_node_ptrs);
51 }
52
53 std::string render_context::render(
54     const template_type& templt, const std::string& prefix)
55 {
56   std::string output;
57   bool prev_eol = true;
58   for (auto& token: templt) {
59     if (prev_eol && prefix.length() != 0)
60       output += m_state.top()->render(*this, {prefix});
61     output += m_state.top()->render(*this, token);
62     prev_eol = token.eol();
63   }
64   return output;
65 }
66
67 std::string render_context::render_partial(
68     const std::string& partial_name, const std::string& prefix)
69 {
70   return m_partials.count(partial_name) ?
71       render(m_partials.at(partial_name), prefix) : "";
72 }