Crow  1.1
A C++ microframework for the web
Loading...
Searching...
No Matches
mustache.h
Go to the documentation of this file.
1/**
2 * \file crow/mustache.h
3 * \brief This file includes the definition of the crow::mustache
4 * namespace and its members.
5 */
6
7#pragma once
8#include <cmath>
9#include <string>
10#include <vector>
11#include <fstream>
12#include <iterator>
13#include <functional>
14#include "crow/json.h"
15#include "crow/logging.h"
16#include "crow/returnable.h"
17#include "crow/utility.h"
18
19namespace crow // NOTE: Already documented in "crow/app.h"
20{
21 /**
22 * \namespace crow::mustache
23 * \brief In this namespace is defined most of the functions and
24 * classes related to template rendering.
25 *
26 * If you are here you might want to read these functions and
27 * classes:
28 *
29 * - \ref template_t
30 * - \ref load_text
31 * - \ref load_text_unsafe
32 * - \ref load
33 * - \ref load_unsafe
34 *
35 * As name suggest, crow uses [mustache](https://en.wikipedia.org/wiki/Mustache_(template_system))
36 * as main template rendering system.
37 *
38 * You may be interested in taking a look at the [Templating guide
39 * page](https://crowcpp.org/master/guides/templating/).
40 */
41 namespace mustache
42 {
43 using context = json::wvalue;
44
45 template_t load(const std::string& filename);
46
47 /**
48 * \class invalid_template_exception
49 * \brief Represents compilation error of an template. Throwed
50 * specially at mustache compile time.
51 */
52 class invalid_template_exception : public std::exception
53 {
54 public:
55 invalid_template_exception(const std::string& msg_):
56 msg("crow::mustache error: " + msg_)
57 {}
58 virtual const char* what() const throw() override
59 {
60 return msg.c_str();
61 }
62 std::string msg;
63 };
64
65 /**
66 * \struct rendered_template
67 * \brief Returned object after call the
68 * \ref template_t::render() method. Its intended to be
69 * returned during a **rule declaration**.
70 *
71 * \see \ref CROW_ROUTE
72 * \see \ref CROW_BP_ROUTE
73 */
74 struct rendered_template : returnable
75 {
76 rendered_template():
77 returnable("text/html") {}
78
79 rendered_template(std::string& body):
80 returnable("text/html"), body_(std::move(body)) {}
81
82 std::string body_;
83
84 std::string dump() const override
85 {
86 return body_;
87 }
88 };
89
90 /**
91 * \enum ActionType
92 * \brief Used in \ref Action to represent different parsing
93 * behaviors.
94 *
95 * \see \ref Action
96 */
97 enum class ActionType
98 {
99 Ignore,
100 Tag,
101 UnescapeTag,
102 OpenBlock,
103 CloseBlock,
104 ElseBlock,
105 Partial,
106 };
107
108 /**
109 * \struct Action
110 * \brief Used during mustache template compilation to
111 * represent parsing actions.
112 *
113 * \see \ref compile
114 * \see \ref template_t
115 */
116 struct Action
117 {
118 bool has_end_match;
119 char tag_char;
120 int start;
121 int end;
122 int pos;
123 ActionType t;
124
125 Action(char tag_char_, ActionType t_, size_t start_, size_t end_, size_t pos_ = 0):
126 has_end_match(false), tag_char(tag_char_), start(static_cast<int>(start_)), end(static_cast<int>(end_)), pos(static_cast<int>(pos_)), t(t_)
127 {
128 }
129
130 bool missing_end_pair() const {
131 switch (t)
132 {
133 case ActionType::Ignore:
134 case ActionType::Tag:
135 case ActionType::UnescapeTag:
136 case ActionType::CloseBlock:
137 case ActionType::Partial:
138 return false;
139
140 // requires a match
141 case ActionType::OpenBlock:
142 case ActionType::ElseBlock:
143 return !has_end_match;
144
145 default:
146 throw std::logic_error("invalid type");
147 }
148 }
149 };
150
151 /**
152 * \class template_t
153 * \brief Compiled mustache template object.
154 *
155 * \warning Use \ref compile instead.
156 */
157 class template_t
158 {
159 public:
160 template_t(std::string body):
161 body_(std::move(body))
162 {
163 // {{ {{# {{/ {{^ {{! {{> {{=
164 parse();
165 }
166
167 private:
168 std::string tag_name(const Action& action) const
169 {
170 return body_.substr(action.start, action.end - action.start);
171 }
172 auto find_context(const std::string& name, const std::vector<const context*>& stack, bool shouldUseOnlyFirstStackValue = false) const -> std::pair<bool, const context&>
173 {
174 if (name == ".")
175 {
176 return {true, *stack.back()};
177 }
178 static json::wvalue empty_str;
179 empty_str = "";
180
181 size_t dotPosition = name.find(".");
182 if (dotPosition == std::string::npos)
183 {
184 for (auto it = stack.rbegin(); it != stack.rend(); ++it)
185 {
186 if ((*it)->t() == json::type::Object)
187 {
188 if ((*it)->count(name))
189 return {true, (**it)[name]};
190 }
191 }
192 }
193 else
194 {
195 std::vector<size_t> dotPositions;
196 dotPositions.push_back(std::string::npos);
197 while (dotPosition != std::string::npos)
198 {
199 dotPositions.push_back(dotPosition);
200 dotPosition = name.find(".", dotPosition + 1);
201 }
202 dotPositions.push_back(name.size());
203 std::vector<std::string> names;
204 names.reserve(dotPositions.size() - 1);
205 for (size_t i = 1; i < dotPositions.size(); i++)
206 names.emplace_back(name.substr(dotPositions[i - 1] + 1, dotPositions[i] - dotPositions[i - 1] - 1));
207
208 for (auto it = stack.rbegin(); it != stack.rend(); ++it)
209 {
210 const context* view = *it;
211 bool found = true;
212 for (auto jt = names.begin(); jt != names.end(); ++jt)
213 {
214 if (view->t() == json::type::Object &&
215 view->count(*jt))
216 {
217 view = &(*view)[*jt];
218 }
219 else
220 {
221 if (shouldUseOnlyFirstStackValue)
222 {
223 return {false, empty_str};
224 }
225 found = false;
226 break;
227 }
228 }
229 if (found)
230 return {true, *view};
231 }
232 }
233
234 return {false, empty_str};
235 }
236
237 void escape(const std::string& in, std::string& out) const
238 {
239 out.reserve(out.size() + in.size());
240 for (auto it = in.begin(); it != in.end(); ++it)
241 {
242 switch (*it)
243 {
244 case '&': out += "&amp;"; break;
245 case '<': out += "&lt;"; break;
246 case '>': out += "&gt;"; break;
247 case '"': out += "&quot;"; break;
248 case '\'': out += "&#39;"; break;
249 case '/': out += "&#x2F;"; break;
250 case '`': out += "&#x60;"; break;
251 case '=': out += "&#x3D;"; break;
252 default: out += *it; break;
253 }
254 }
255 }
256
257 bool isTagInsideObjectBlock(const int& current, const std::vector<const context*>& stack) const
258 {
259 int openedBlock = 0;
260 for (int i = current; i > 0; --i)
261 {
262 auto& action = actions_[i - 1];
263
264 if (action.t == ActionType::OpenBlock)
265 {
266 if (openedBlock == 0 && (*stack.rbegin())->t() == json::type::Object)
267 {
268 return true;
269 }
270 --openedBlock;
271 }
272 else if (action.t == ActionType::CloseBlock)
273 {
274 ++openedBlock;
275 }
276 }
277
278 return false;
279 }
280
281 static bool is_number_zero(const context& ctx)
282 {
283 switch (ctx.nt)
284 {
285 case json::num_type::Signed_integer:
286 return ctx.num.si == 0;
287 case json::num_type::Unsigned_integer:
288 return ctx.num.ui == 0;
289 case json::num_type::Floating_point:
290 case json::num_type::Double_precision_floating_point:
291 return std::fpclassify(ctx.num.d) == FP_ZERO;
292 default:
293 return false;
294 }
295 }
296
297 void render_internal(int actionBegin, int actionEnd, std::vector<const context*>& stack, std::string& out, int indent) const
298 {
299 int current = actionBegin;
300
301 if (indent)
302 out.insert(out.size(), indent, ' ');
303
304 while (current < actionEnd)
305 {
306 auto& fragment = fragments_[current];
307 auto& action = actions_[current];
308 render_fragment(fragment, indent, out);
309 switch (action.t)
310 {
311 case ActionType::Ignore:
312 // do nothing
313 break;
314 case ActionType::Partial:
315 {
316 std::string partial_name = tag_name(action);
317 auto partial_templ = load(partial_name);
318 int partial_indent = action.pos;
319 partial_templ.render_internal(0, partial_templ.fragments_.size() - 1, stack, out, partial_indent ? indent + partial_indent : 0);
320 }
321 break;
322 case ActionType::UnescapeTag:
323 case ActionType::Tag:
324 {
325 bool shouldUseOnlyFirstStackValue = false;
326 if (isTagInsideObjectBlock(current, stack))
327 {
328 shouldUseOnlyFirstStackValue = true;
329 }
330 auto optional_ctx = find_context(tag_name(action), stack, shouldUseOnlyFirstStackValue);
331 auto& ctx = optional_ctx.second;
332 switch (ctx.t())
333 {
334 case json::type::False:
335 case json::type::True:
336 case json::type::Number:
337 out += ctx.dump();
338 break;
339 case json::type::String:
340 if (action.t == ActionType::Tag)
341 escape(ctx.s, out);
342 else
343 out += ctx.s;
344 break;
345 case json::type::Function:
346 {
347 std::string execute_result = ctx.execute();
348 // render the lambda's result once; rendering it again would parse
349 // the values it interpolated as template tags
350 if (execute_result.find("{{") != std::string::npos)
351 {
352 template_t result_plug(execute_result);
353 execute_result = result_plug.render_string(*(stack[0]));
354 }
355
356 if (action.t == ActionType::Tag)
357 escape(execute_result, out);
358 else
359 out += execute_result;
360 }
361 break;
362 default:
363 throw std::runtime_error("not implemented tag type" + utility::lexical_cast<std::string>(static_cast<int>(ctx.t())));
364 }
365 }
366 break;
367 case ActionType::ElseBlock:
368 {
369 static context nullContext;
370 auto optional_ctx = find_context(tag_name(action), stack);
371 if (!optional_ctx.first)
372 {
373 stack.emplace_back(&nullContext);
374 break;
375 }
376
377 auto& ctx = optional_ctx.second;
378 switch (ctx.t())
379 {
380 case json::type::List:
381 if (ctx.l && !ctx.l->empty())
382 current = action.pos;
383 else
384 stack.emplace_back(&nullContext);
385 break;
386 case json::type::False:
387 case json::type::Null:
388 stack.emplace_back(&nullContext);
389 break;
390 case json::type::Number:
391 if (is_number_zero(ctx))
392 stack.emplace_back(&nullContext);
393 else
394 current = action.pos;
395 break;
396 default:
397 current = action.pos;
398 break;
399 }
400 break;
401 }
402 case ActionType::OpenBlock:
403 {
404 auto optional_ctx = find_context(tag_name(action), stack);
405 if (!optional_ctx.first)
406 {
407 current = action.pos;
408 break;
409 }
410
411 auto& ctx = optional_ctx.second;
412 switch (ctx.t())
413 {
414 case json::type::List:
415 if (ctx.l)
416 for (auto it = ctx.l->begin(); it != ctx.l->end(); ++it)
417 {
418 stack.push_back(&*it);
419 render_internal(current + 1, action.pos, stack, out, indent);
420 stack.pop_back();
421 }
422 current = action.pos;
423 break;
424 case json::type::Number:
425 if (is_number_zero(ctx))
426 current = action.pos;
427 else
428 stack.push_back(&ctx);
429 break;
430 case json::type::String:
431 case json::type::Object:
432 case json::type::True:
433 stack.push_back(&ctx);
434 break;
435 case json::type::False:
436 case json::type::Null:
437 current = action.pos;
438 break;
439 default:
440 throw std::runtime_error("{{#: not implemented context type: " + utility::lexical_cast<std::string>(static_cast<int>(ctx.t())));
441 break;
442 }
443 break;
444 }
445 case ActionType::CloseBlock:
446 stack.pop_back();
447 break;
448 default:
449 throw std::runtime_error("not implemented " + utility::lexical_cast<std::string>(static_cast<int>(action.t)));
450 }
451 current++;
452 }
453 auto& fragment = fragments_[actionEnd];
454 render_fragment(fragment, indent, out);
455 }
456 void render_fragment(const std::pair<int, int> fragment, int indent, std::string& out) const
457 {
458 if (indent)
459 {
460 for (int i = fragment.first; i < fragment.second; i++)
461 {
462 out += body_[i];
463 if (body_[i] == '\n' && i + 1 != static_cast<int>(body_.size()))
464 out.insert(out.size(), indent, ' ');
465 }
466 }
467 else
468 out.insert(out.size(), body_, fragment.first, fragment.second - fragment.first);
469 }
470
471 public:
472 /// Output a returnable template from this mustache template
474 {
475 context empty_ctx;
476 std::vector<const context*> stack;
477 stack.emplace_back(&empty_ctx);
478
479 std::string ret;
480 render_internal(0, fragments_.size() - 1, stack, ret, 0);
481 return rendered_template(ret);
482 }
483
484 /// Apply the values from the context provided and output a returnable template from this mustache template
485 rendered_template render(const context& ctx) const
486 {
487 std::vector<const context*> stack;
488 stack.emplace_back(&ctx);
489
490 std::string ret;
491 render_internal(0, fragments_.size() - 1, stack, ret, 0);
492 return rendered_template(ret);
493 }
494
495 /// Apply the values from the context provided and output a returnable template from this mustache template
496 rendered_template render(const context&& ctx) const
497 {
498 return render(ctx);
499 }
500
501 /// Output a returnable template from this mustache template
502 std::string render_string() const
503 {
504 context empty_ctx;
505 std::vector<const context*> stack;
506 stack.emplace_back(&empty_ctx);
507
508 std::string ret;
509 render_internal(0, fragments_.size() - 1, stack, ret, 0);
510 return ret;
511 }
512
513 /// Apply the values from the context provided and output a returnable template from this mustache template
514 std::string render_string(const context& ctx) const
515 {
516 std::vector<const context*> stack;
517 stack.emplace_back(&ctx);
518
519 std::string ret;
520 render_internal(0, fragments_.size() - 1, stack, ret, 0);
521 return ret;
522 }
523
524 private:
525 void parse()
526 {
527 std::string tag_open = "{{";
528 std::string tag_close = "}}";
529
530 std::vector<int> blockPositions;
531
532 size_t current = 0;
533 while (1)
534 {
535 size_t idx = body_.find(tag_open, current);
536 if (idx == body_.npos)
537 {
538 fragments_.emplace_back(static_cast<int>(current), static_cast<int>(body_.size()));
539 actions_.emplace_back('!', ActionType::Ignore, 0, 0);
540 break;
541 }
542 fragments_.emplace_back(static_cast<int>(current), static_cast<int>(idx));
543
544 idx += tag_open.size();
545 size_t endIdx = body_.find(tag_close, idx);
546 if (endIdx == idx)
547 {
548 throw invalid_template_exception("empty tag is not allowed");
549 }
550 if (endIdx == body_.npos)
551 {
552 // error, no matching tag
553 throw invalid_template_exception("not matched opening tag");
554 }
555 current = endIdx + tag_close.size();
556 char tag_char = body_[idx];
557 switch (tag_char)
558 {
559 case '#':
560 idx++;
561 while (body_[idx] == ' ')
562 idx++;
563 while (body_[endIdx - 1] == ' ')
564 endIdx--;
565 blockPositions.emplace_back(static_cast<int>(actions_.size()));
566 actions_.emplace_back(tag_char, ActionType::OpenBlock, idx, endIdx);
567 break;
568 case '/':
569 idx++;
570 while (body_[idx] == ' ')
571 idx++;
572 while (body_[endIdx - 1] == ' ')
573 endIdx--;
574 {
575 if (blockPositions.empty())
576 {
577 throw invalid_template_exception(
578 std::string("unexpected closing tag: ")
579 + body_.substr(idx, endIdx - idx)
580 );
581 }
582 auto& matched = actions_[blockPositions.back()];
583 if (body_.compare(idx, endIdx - idx,
584 body_, matched.start, matched.end - matched.start) != 0)
585 {
586 throw invalid_template_exception(
587 std::string("not matched {{")
588 + matched.tag_char
589 + "{{/ pair: "
590 + body_.substr(matched.start, matched.end - matched.start) + ", "
591 + body_.substr(idx, endIdx - idx)
592 );
593 }
594 matched.pos = static_cast<int>(actions_.size());
595 matched.has_end_match = true;
596 }
597 actions_.emplace_back(tag_char, ActionType::CloseBlock, idx, endIdx, blockPositions.back());
598 blockPositions.pop_back();
599 break;
600 case '^':
601 idx++;
602 while (body_[idx] == ' ')
603 idx++;
604 while (body_[endIdx - 1] == ' ')
605 endIdx--;
606 blockPositions.emplace_back(static_cast<int>(actions_.size()));
607 actions_.emplace_back(tag_char, ActionType::ElseBlock, idx, endIdx);
608 break;
609 case '!':
610 // do nothing action
611 actions_.emplace_back(tag_char, ActionType::Ignore, idx + 1, endIdx);
612 break;
613 case '>': // partial
614 idx++;
615 while (body_[idx] == ' ')
616 idx++;
617 while (body_[endIdx - 1] == ' ')
618 endIdx--;
619 actions_.emplace_back(tag_char, ActionType::Partial, idx, endIdx);
620 break;
621 case '{':
622 if (tag_open != "{{" || tag_close != "}}")
623 throw invalid_template_exception("cannot use triple mustache when delimiter changed");
624
625 idx++;
626 if (body_[endIdx + 2] != '}')
627 {
628 throw invalid_template_exception("{{{: }}} not matched");
629 }
630 while (body_[idx] == ' ')
631 idx++;
632 while (body_[endIdx - 1] == ' ')
633 endIdx--;
634 actions_.emplace_back(tag_char, ActionType::UnescapeTag, idx, endIdx);
635 current++;
636 break;
637 case '&':
638 idx++;
639 while (body_[idx] == ' ')
640 idx++;
641 while (body_[endIdx - 1] == ' ')
642 endIdx--;
643 actions_.emplace_back(tag_char, ActionType::UnescapeTag, idx, endIdx);
644 break;
645 case '=':
646 // tag itself is no-op
647 idx++;
648 actions_.emplace_back(tag_char, ActionType::Ignore, idx, endIdx);
649 endIdx--;
650 if (body_[endIdx] != '=')
651 throw invalid_template_exception("{{=: not matching = tag: " + body_.substr(idx, endIdx - idx));
652 endIdx--;
653 while (body_[idx] == ' ')
654 idx++;
655 while (body_[endIdx] == ' ')
656 endIdx--;
657 endIdx++;
658 {
659 bool succeeded = false;
660 for (size_t i = idx; i < endIdx; i++)
661 {
662 if (body_[i] == ' ')
663 {
664 tag_open = body_.substr(idx, i - idx);
665 while (body_[i] == ' ')
666 i++;
667 tag_close = body_.substr(i, endIdx - i);
668 if (tag_open.empty())
669 throw invalid_template_exception("{{=: empty open tag");
670 if (tag_close.empty())
671 throw invalid_template_exception("{{=: empty close tag");
672
673 if (tag_close.find(" ") != tag_close.npos)
674 throw invalid_template_exception("{{=: invalid open/close tag: " + tag_open + " " + tag_close);
675 succeeded = true;
676 break;
677 }
678 }
679 if (!succeeded)
680 throw invalid_template_exception("{{=: cannot find space between new open/close tags");
681 }
682 break;
683 default:
684 // normal tag case;
685 while (body_[idx] == ' ')
686 idx++;
687 while (body_[endIdx - 1] == ' ')
688 endIdx--;
689 actions_.emplace_back(tag_char, ActionType::Tag, idx, endIdx);
690 break;
691 }
692 }
693
694 // ensure no unmatched tags
695 for (int i = 0; i < static_cast<int>(actions_.size()); i++)
696 {
697 if (actions_[i].missing_end_pair())
698 {
699 throw invalid_template_exception(
700 std::string("open tag has no matching end tag {{")
701 + actions_[i].tag_char
702 + " {{/ pair: "
703 + body_.substr(actions_[i].start, actions_[i].end - actions_[i].start)
704 );
705 }
706 }
707
708 // removing standalones
709 for (int i = static_cast<int>(actions_.size()) - 2; i >= 0; i--)
710 {
711 if (actions_[i].t == ActionType::Tag || actions_[i].t == ActionType::UnescapeTag)
712 continue;
713 auto& fragment_before = fragments_[i];
714 auto& fragment_after = fragments_[i + 1];
715 bool is_last_action = i == static_cast<int>(actions_.size()) - 2;
716 bool all_space_before = true;
717 int j, k;
718 for (j = fragment_before.second - 1; j >= fragment_before.first; j--)
719 {
720 if (body_[j] != ' ')
721 {
722 all_space_before = false;
723 break;
724 }
725 }
726 if (all_space_before && i > 0)
727 continue;
728 if (!all_space_before && body_[j] != '\n')
729 continue;
730 bool all_space_after = true;
731 for (k = fragment_after.first; k < static_cast<int>(body_.size()) && k < fragment_after.second; k++)
732 {
733 if (body_[k] != ' ')
734 {
735 all_space_after = false;
736 break;
737 }
738 }
739 if (all_space_after && !is_last_action)
740 continue;
741 if (!all_space_after &&
742 !(
743 body_[k] == '\n' ||
744 (body_[k] == '\r' &&
745 k + 1 < static_cast<int>(body_.size()) &&
746 body_[k + 1] == '\n')))
747 continue;
748 if (actions_[i].t == ActionType::Partial)
749 {
750 actions_[i].pos = fragment_before.second - j - 1;
751 }
752 fragment_before.second = j + 1;
753 if (!all_space_after)
754 {
755 if (body_[k] == '\n')
756 k++;
757 else
758 k += 2;
759 fragment_after.first = k;
760 }
761 }
762 }
763
764 std::vector<std::pair<int, int>> fragments_;
765 std::vector<Action> actions_;
766 std::string body_;
767 };
768
769 /// \brief The function that compiles a source into a mustache
770 /// template.
771 inline template_t compile(const std::string& body)
772 {
773 return template_t(body);
774 }
775
776 namespace detail
777 {
778 inline std::string& get_template_base_directory_ref()
779 {
780 static std::string template_base_directory = "templates";
781 return template_base_directory;
782 }
783
784 /// A base directory not related to any blueprint
786 {
787 static std::string template_base_directory = "templates";
788 return template_base_directory;
789 }
790 } // namespace detail
791
792 /// \brief The default way that \ref load, \ref load_unsafe,
793 /// \ref load_text and \ref load_text_unsafe use to read the
794 /// contents of a file.
795 inline std::string default_loader(const std::string& filename)
796 {
797 std::string path = detail::get_template_base_directory_ref();
798 std::ifstream inf(utility::join_path(path, filename));
799 if (!inf)
800 {
801 CROW_LOG_WARNING << "Template \"" << filename << "\" not found.";
802 return {};
803 }
804 return {std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>()};
805 }
806
807 namespace detail
808 {
809 inline std::function<std::string(std::string)>& get_loader_ref()
810 {
811 static std::function<std::string(std::string)> loader = default_loader;
812 return loader;
813 }
814 } // namespace detail
815
816 /// \brief Defines the templates directory path at **route
817 /// level**. By default is `templates/`.
818 inline void set_base(const std::string& path)
819 {
820 auto& base = detail::get_template_base_directory_ref();
821 base = path;
822 if (base.back() != '\\' &&
823 base.back() != '/')
824 {
825 base += '/';
826 }
827 }
828
829 /// \brief Defines the templates directory path at **global
830 /// level**. By default is `templates/`.
831 inline void set_global_base(const std::string& path)
832 {
834 base = path;
835 if (base.back() != '\\' &&
836 base.back() != '/')
837 {
838 base += '/';
839 }
840 }
841
842 /// \brief Change the way that \ref load, \ref load_unsafe,
843 /// \ref load_text and \ref load_text_unsafe reads a file.
844 ///
845 /// By default, the previously mentioned functions load files
846 /// using \ref default_loader, that only reads a file and
847 /// returns a std::string.
848 inline void set_loader(std::function<std::string(std::string)> loader)
849 {
850 detail::get_loader_ref() = std::move(loader);
851 }
852
853 /// \brief Open, read and sanitize a file but returns a
854 /// std::string without a previous rendering process.
855 ///
856 /// Except for the **sanitize process** this function does the
857 /// almost the same thing that \ref load_text_unsafe.
858 inline std::string load_text(const std::string& filename)
859 {
860 std::string filename_sanitized(filename);
861 utility::sanitize_filename(filename_sanitized);
862 return detail::get_loader_ref()(filename_sanitized);
863 }
864
865 /// \brief Open and read a file but returns a std::string
866 /// without a previous rendering process.
867 ///
868 /// This function is more like a helper to reduce code like
869 /// this...
870 ///
871 /// ```cpp
872 /// std::ifstream file("home.html");
873 /// return std::string({std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()});
874 /// ```
875 ///
876 /// ... Into this...
877 ///
878 /// ```cpp
879 /// return load("home.html");
880 /// ```
881 ///
882 /// \warning Usually \ref load_text is more recommended to use
883 /// instead because it may prevent some [XSS Attacks](https://en.wikipedia.org/wiki/Cross-site_scripting).
884 /// **Never blindly trust your users!**
885 inline std::string load_text_unsafe(const std::string& filename)
886 {
887 return detail::get_loader_ref()(filename);
888 }
889
890 /// \brief Open, read and renders a file using a mustache
891 /// compiler. It also sanitize the input before compilation.
892 inline template_t load(const std::string& filename)
893 {
894 std::string filename_sanitized(filename);
895 utility::sanitize_filename(filename_sanitized);
896 return compile(detail::get_loader_ref()(filename_sanitized));
897 }
898
899 /// \brief Open, read and renders a file using a mustache
900 /// compiler. But it **do not** sanitize the input before
901 /// compilation.
902 ///
903 /// \warning Usually \ref load is more recommended to use
904 /// instead because it may prevent some [XSS Attacks](https://en.wikipedia.org/wiki/Cross-site_scripting).
905 /// **Never blindly trust your users!**
906 inline template_t load_unsafe(const std::string& filename)
907 {
908 return compile(detail::get_loader_ref()(filename));
909 }
910 } // namespace mustache
911} // namespace crow
JSON write value.
Definition json.h:1378
Compiled mustache template object.
Definition mustache.h:158
std::string render_string() const
Output a returnable template from this mustache template.
Definition mustache.h:502
rendered_template render() const
Output a returnable template from this mustache template.
Definition mustache.h:473
rendered_template render(const context &ctx) const
Apply the values from the context provided and output a returnable template from this mustache templa...
Definition mustache.h:485
rendered_template render(const context &&ctx) const
Apply the values from the context provided and output a returnable template from this mustache templa...
Definition mustache.h:496
std::string render_string(const context &ctx) const
Apply the values from the context provided and output a returnable template from this mustache templa...
Definition mustache.h:514
std::string & get_global_template_base_directory_ref()
A base directory not related to any blueprint.
Definition mustache.h:785
In this namespace is defined most of the functions and classes related to template rendering.
Definition json.h:35
void set_loader(std::function< std::string(std::string)> loader)
Change the way that load, load_unsafe, load_text and load_text_unsafe reads a file.
Definition mustache.h:848
template_t compile(const std::string &body)
The function that compiles a source into a mustache template.
Definition mustache.h:771
std::string load_text_unsafe(const std::string &filename)
Open and read a file but returns a std::string without a previous rendering process.
Definition mustache.h:885
void set_global_base(const std::string &path)
Defines the templates directory path at global level. By default is templates/.
Definition mustache.h:831
std::string default_loader(const std::string &filename)
The default way that load, load_unsafe, load_text and load_text_unsafe use to read the contents of a ...
Definition mustache.h:795
void set_base(const std::string &path)
Defines the templates directory path at route level. By default is templates/.
Definition mustache.h:818
std::string load_text(const std::string &filename)
Open, read and sanitize a file but returns a std::string without a previous rendering process.
Definition mustache.h:858
template_t load(const std::string &filename)
Open, read and renders a file using a mustache compiler. It also sanitize the input before compilatio...
Definition mustache.h:892
ActionType
Used in Action to represent different parsing behaviors.
Definition mustache.h:98
template_t load_unsafe(const std::string &filename)
Open, read and renders a file using a mustache compiler. But it do not sanitize the input before comp...
Definition mustache.h:906
The main namespace of the library. In this namespace is defined the most important classes and functi...
Used during mustache template compilation to represent parsing actions.
Definition mustache.h:117
Returned object after call the template_t::render() method. Its intended to be returned during a rule...
Definition mustache.h:75