mustache.hpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. //
  2. // Copyright 2015 Kevin Wojniak
  3. //
  4. // Boost Software License - Version 1.0 - August 17th, 2003
  5. //
  6. // Permission is hereby granted, free of charge, to any person or organization
  7. // obtaining a copy of the software and accompanying documentation covered by
  8. // this license (the "Software") to use, reproduce, display, distribute,
  9. // execute, and transmit the Software, and to prepare derivative works of the
  10. // Software, and to permit third-parties to whom the Software is furnished to
  11. // do so, all subject to the following:
  12. //
  13. // The copyright notices in the Software and this entire statement, including
  14. // the above license grant, this restriction and the following disclaimer,
  15. // must be included in all copies of the Software, in whole or in part, and
  16. // all derivative works of the Software, unless such copies or derivative
  17. // works are solely in the form of machine-executable object code generated by
  18. // a source language processor.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  23. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  24. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  25. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  26. // DEALINGS IN THE SOFTWARE.
  27. //
  28. #ifndef MUSTACHE_HPP
  29. #define MUSTACHE_HPP
  30. #include <iostream>
  31. #include <sstream>
  32. #include <vector>
  33. #include <functional>
  34. #include <unordered_map>
  35. #include <memory>
  36. namespace Mustache {
  37. template <typename StringType>
  38. StringType trim(const StringType& s) {
  39. auto it = s.begin();
  40. while (it != s.end() && isspace(static_cast<int>(*it))) {
  41. it++;
  42. }
  43. auto rit = s.rbegin();
  44. while (rit.base() != it && isspace(*rit)) {
  45. rit++;
  46. }
  47. return {it, rit.base()};
  48. }
  49. template <typename StringType>
  50. StringType escape(const StringType& s) {
  51. StringType ret;
  52. ret.reserve(s.size()*2);
  53. for (const auto ch : s) {
  54. switch (static_cast<char>(ch)) {
  55. case '&':
  56. ret.append("&amp;");
  57. break;
  58. case '<':
  59. ret.append("&lt;");
  60. break;
  61. case '>':
  62. ret.append("&gt;");
  63. break;
  64. case '\"':
  65. ret.append("&quot;");
  66. break;
  67. case '\'':
  68. ret.append("&apos;");
  69. break;
  70. default:
  71. ret.append(1, ch);
  72. break;
  73. }
  74. }
  75. return ret;
  76. }
  77. template <typename StringType>
  78. class Data {
  79. public:
  80. enum class Type {
  81. Object,
  82. String,
  83. List,
  84. True,
  85. False,
  86. Partial,
  87. Lambda,
  88. Invalid,
  89. };
  90. using ObjectType = std::unordered_map<StringType, Data>;
  91. using ListType = std::vector<Data>;
  92. using PartialType = std::function<StringType()>;
  93. using LambdaType = std::function<Data(const StringType&)>;
  94. // Construction
  95. Data() : Data(Type::Object) {
  96. }
  97. Data(const StringType& string) : type_{Type::String} {
  98. str_.reset(new StringType(string));
  99. }
  100. Data(const typename StringType::value_type* string) : type_{Type::String} {
  101. str_.reset(new StringType(string));
  102. }
  103. Data(const ListType& list) : type_{Type::List} {
  104. list_.reset(new ListType(list));
  105. }
  106. Data(Type type) : type_{type} {
  107. switch (type_) {
  108. case Type::Object:
  109. obj_.reset(new ObjectType);
  110. break;
  111. case Type::String:
  112. str_.reset(new StringType);
  113. break;
  114. case Type::List:
  115. list_.reset(new ListType);
  116. break;
  117. default:
  118. break;
  119. }
  120. }
  121. Data(const StringType& name, const Data& var) : Data{} {
  122. set(name, var);
  123. }
  124. Data(const PartialType& partial) : type_{Type::Partial} {
  125. partial_.reset(new PartialType(partial));
  126. }
  127. Data(const LambdaType& lambda) : type_{Type::Lambda} {
  128. lambda_.reset(new LambdaType(lambda));
  129. }
  130. static Data List() {
  131. return {Data::Type::List};
  132. }
  133. // Copying
  134. Data(const Data& data) : type_(data.type_) {
  135. if (data.obj_) {
  136. obj_.reset(new ObjectType(*data.obj_));
  137. } else if (data.str_) {
  138. str_.reset(new StringType(*data.str_));
  139. } else if (data.list_) {
  140. list_.reset(new ListType(*data.list_));
  141. } else if (data.partial_) {
  142. partial_.reset(new PartialType(*data.partial_));
  143. } else if (data.lambda_) {
  144. lambda_.reset(new LambdaType(*data.lambda_));
  145. }
  146. }
  147. // Assignment
  148. Data& operator= (const Data& data) {
  149. if (&data != this) {
  150. type_ = data.type_;
  151. obj_.reset();
  152. str_.reset();
  153. list_.reset();
  154. partial_.reset();
  155. lambda_.reset();
  156. if (data.obj_) {
  157. obj_.reset(new ObjectType(*data.obj_));
  158. } else if (data.str_) {
  159. str_.reset(new StringType(*data.str_));
  160. } else if (data.list_) {
  161. list_.reset(new ListType(*data.list_));
  162. } else if (data.partial_) {
  163. partial_.reset(new PartialType(*data.partial_));
  164. } else if (data.lambda_) {
  165. lambda_.reset(new LambdaType(*data.lambda_));
  166. }
  167. }
  168. return *this;
  169. }
  170. // Move
  171. Data(Data&& data) : type_{data.type_} {
  172. if (data.obj_) {
  173. obj_ = std::move(data.obj_);
  174. } else if (data.str_) {
  175. str_ = std::move(data.str_);
  176. } else if (data.list_) {
  177. list_ = std::move(data.list_);
  178. } else if (data.partial_) {
  179. partial_ = std::move(data.partial_);
  180. } else if (data.lambda_) {
  181. lambda_ = std::move(data.lambda_);
  182. }
  183. data.type_ = Data::Type::Invalid;
  184. }
  185. Data& operator= (Data&& data) {
  186. if (this != &data) {
  187. obj_.reset();
  188. str_.reset();
  189. list_.reset();
  190. partial_.reset();
  191. lambda_.reset();
  192. if (data.obj_) {
  193. obj_ = std::move(data.obj_);
  194. } else if (data.str_) {
  195. str_ = std::move(data.str_);
  196. } else if (data.list_) {
  197. list_ = std::move(data.list_);
  198. } else if (data.partial_) {
  199. partial_ = std::move(data.partial_);
  200. } else if (data.lambda_) {
  201. lambda_ = std::move(data.lambda_);
  202. }
  203. type_ = data.type_;
  204. data.type_ = Data::Type::Invalid;
  205. }
  206. return *this;
  207. }
  208. // Type info
  209. Type type() const {
  210. return type_;
  211. }
  212. bool isObject() const {
  213. return type_ == Type::Object;
  214. }
  215. bool isString() const {
  216. return type_ == Type::String;
  217. }
  218. bool isList() const {
  219. return type_ == Type::List;
  220. }
  221. bool isBool() const {
  222. return type_ == Type::True || type_ == Type::False;
  223. }
  224. bool isTrue() const {
  225. return type_ == Type::True;
  226. }
  227. bool isFalse() const {
  228. return type_ == Type::False;
  229. }
  230. bool isPartial() const {
  231. return type_ == Type::Partial;
  232. }
  233. bool isLambda() const {
  234. return type_ == Type::Lambda;
  235. }
  236. // Object data
  237. void set(const StringType& name, const Data& var) {
  238. if (isObject()) {
  239. obj_->insert(std::pair<StringType,Data>{name, var});
  240. }
  241. }
  242. bool exists(const StringType& name) const {
  243. if (isObject() && obj_->find(name) == obj_->end()) {
  244. return true;
  245. }
  246. return false;
  247. }
  248. const Data* get(const StringType& name) const {
  249. if (!isObject()) {
  250. return nullptr;
  251. }
  252. const auto& it = obj_->find(name);
  253. if (it == obj_->end()) {
  254. return nullptr;
  255. }
  256. return &it->second;
  257. }
  258. // List data
  259. void push_back(const Data& var) {
  260. if (isList()) {
  261. list_->push_back(var);
  262. }
  263. }
  264. const ListType& list() const {
  265. return *list_;
  266. }
  267. bool isEmptyList() const {
  268. return isList() && list_->empty();
  269. }
  270. bool isNonEmptyList() const {
  271. return isList() && !list_->empty();
  272. }
  273. Data& operator<< (const Data& data) {
  274. push_back(data);
  275. return *this;
  276. }
  277. // String data
  278. const StringType& stringValue() const {
  279. return *str_;
  280. }
  281. Data& operator[] (const StringType& key) {
  282. return (*obj_)[key];
  283. }
  284. const PartialType& partial() const {
  285. return (*partial_);
  286. }
  287. const LambdaType& lambda() const {
  288. return (*lambda_);
  289. }
  290. Data<StringType> callLambda(const StringType& text) const {
  291. return (*lambda_)(text);
  292. }
  293. private:
  294. Type type_;
  295. std::unique_ptr<ObjectType> obj_;
  296. std::unique_ptr<StringType> str_;
  297. std::unique_ptr<ListType> list_;
  298. std::unique_ptr<PartialType> partial_;
  299. std::unique_ptr<LambdaType> lambda_;
  300. };
  301. template <typename StringType>
  302. class Mustache {
  303. public:
  304. Mustache(const StringType& input) {
  305. Context ctx;
  306. parse(input, ctx);
  307. }
  308. bool isValid() const {
  309. return errorMessage_.empty();
  310. }
  311. const StringType& errorMessage() const {
  312. return errorMessage_;
  313. }
  314. template <typename StreamType>
  315. StreamType& render(const Data<StringType>& data, StreamType& stream) {
  316. render(data, [&stream](const StringType& str) {
  317. stream << str;
  318. });
  319. return stream;
  320. }
  321. StringType render(const Data<StringType>& data) {
  322. std::basic_ostringstream<typename StringType::value_type> ss;
  323. return render(data, ss).str();
  324. }
  325. using RenderHandler = std::function<void(const StringType&)>;
  326. void render(const Data<StringType>& data, const RenderHandler& handler) {
  327. Context ctx{&data};
  328. render(handler, ctx);
  329. }
  330. private:
  331. using StringSizeType = typename StringType::size_type;
  332. class DelimiterSet {
  333. public:
  334. StringType begin;
  335. StringType end;
  336. DelimiterSet() {
  337. reset();
  338. }
  339. DelimiterSet(const StringType& b, const StringType& e) : begin(b), end(e) {}
  340. bool isDefault() const { return begin == defaultBegin() && end == defaultEnd(); }
  341. void reset() {
  342. begin = defaultBegin();
  343. end = defaultEnd();
  344. }
  345. static StringType defaultBegin() {
  346. return StringType(2, '{');
  347. }
  348. static StringType defaultEnd() {
  349. return StringType(2, '}');
  350. }
  351. };
  352. class Tag {
  353. public:
  354. enum class Type {
  355. Invalid,
  356. Variable,
  357. UnescapedVariable,
  358. SectionBegin,
  359. SectionEnd,
  360. SectionBeginInverted,
  361. Comment,
  362. Partial,
  363. SetDelimiter,
  364. };
  365. StringType name;
  366. Type type = Type::Invalid;
  367. std::shared_ptr<StringType> sectionText;
  368. std::shared_ptr<DelimiterSet> delimiterSet;
  369. bool isSectionBegin() const {
  370. return type == Type::SectionBegin || type == Type::SectionBeginInverted;
  371. }
  372. bool isSectionEnd() const {
  373. return type == Type::SectionEnd;
  374. }
  375. };
  376. class Component {
  377. public:
  378. StringType text;
  379. Tag tag;
  380. std::vector<Component> children;
  381. StringSizeType position = StringType::npos;
  382. bool isText() const {
  383. return tag.type == Tag::Type::Invalid;
  384. }
  385. bool isTag() const {
  386. return tag.type != Tag::Type::Invalid;
  387. }
  388. Component() {}
  389. Component(const StringType& t, StringSizeType p) : text(t), position(p) {}
  390. };
  391. class Context {
  392. public:
  393. using DataType = Data<StringType>;
  394. Context(const DataType* data) {
  395. push(data);
  396. }
  397. Context() {
  398. }
  399. void push(const DataType* data) {
  400. items_.insert(items_.begin(), data);
  401. }
  402. void pop() {
  403. items_.erase(items_.begin());
  404. }
  405. static std::vector<StringType> split(const StringType& s, char delim) {
  406. std::vector<StringType> elems;
  407. std::stringstream ss(s);
  408. std::string item;
  409. while (std::getline(ss, item, delim)) {
  410. elems.push_back(item);
  411. }
  412. return elems;
  413. }
  414. const DataType* get(const StringType& name) const {
  415. // process {{.}} name
  416. if (name.size() == 1 && name.at(0) == '.') {
  417. return items_.front();
  418. }
  419. // process {{a.b.c}} name
  420. if (name.find('.', 1) != StringType::npos) {
  421. const DataType* var{items_.front()};
  422. for (const auto& n : split(name, '.')) {
  423. var = var->get(n);
  424. if (!var) {
  425. return nullptr;
  426. }
  427. }
  428. return var;
  429. }
  430. // process normal name
  431. for (const auto& item : items_) {
  432. const auto var = item->get(name);
  433. if (var) {
  434. return var;
  435. }
  436. }
  437. return nullptr;
  438. }
  439. Context(const Context&) = delete;
  440. Context& operator= (const Context&) = delete;
  441. DelimiterSet delimiterSet;
  442. private:
  443. std::vector<const DataType*> items_;
  444. };
  445. class ContextPusher {
  446. public:
  447. ContextPusher(Context& ctx, const Data<StringType>* data) : ctx_(ctx) {
  448. ctx.push(data);
  449. }
  450. ~ContextPusher() {
  451. ctx_.pop();
  452. }
  453. ContextPusher(const ContextPusher&) = delete;
  454. ContextPusher& operator= (const ContextPusher&) = delete;
  455. private:
  456. Context& ctx_;
  457. };
  458. Mustache(const StringType& input, Context& ctx) {
  459. parse(input, ctx);
  460. }
  461. void parse(const StringType& input, Context& ctx) {
  462. using streamstring = std::basic_ostringstream<typename StringType::value_type>;
  463. const StringType braceDelimiterEndUnescaped(3, '}');
  464. const StringSizeType inputSize{input.size()};
  465. bool currentDelimiterIsBrace{ctx.delimiterSet.isDefault()};
  466. std::vector<Component*> sections{&rootComponent_};
  467. std::vector<StringSizeType> sectionStarts;
  468. StringSizeType inputPosition{0};
  469. while (inputPosition != inputSize) {
  470. // Find the next tag start delimiter
  471. const StringSizeType tagLocationStart{input.find(ctx.delimiterSet.begin, inputPosition)};
  472. if (tagLocationStart == StringType::npos) {
  473. // No tag found. Add the remaining text.
  474. const Component comp{{input, inputPosition, inputSize - inputPosition}, inputPosition};
  475. sections.back()->children.push_back(comp);
  476. break;
  477. } else if (tagLocationStart != inputPosition) {
  478. // Tag found, add text up to this tag.
  479. const Component comp{{input, inputPosition, tagLocationStart - inputPosition}, inputPosition};
  480. sections.back()->children.push_back(comp);
  481. }
  482. // Find the next tag end delimiter
  483. StringSizeType tagContentsLocation{tagLocationStart + ctx.delimiterSet.begin.size()};
  484. const bool tagIsUnescapedVar{currentDelimiterIsBrace && tagLocationStart != (inputSize - 2) && input.at(tagContentsLocation) == ctx.delimiterSet.begin.at(0)};
  485. const StringType& currentTagDelimiterEnd{tagIsUnescapedVar ? braceDelimiterEndUnescaped : ctx.delimiterSet.end};
  486. const auto currentTagDelimiterEndSize = currentTagDelimiterEnd.size();
  487. if (tagIsUnescapedVar) {
  488. ++tagContentsLocation;
  489. }
  490. StringSizeType tagLocationEnd{input.find(currentTagDelimiterEnd, tagContentsLocation)};
  491. if (tagLocationEnd == StringType::npos) {
  492. streamstring ss;
  493. ss << "Unclosed tag at " << tagLocationStart;
  494. errorMessage_.assign(ss.str());
  495. return;
  496. }
  497. // Parse tag
  498. const StringType tagContents{trim(StringType{input, tagContentsLocation, tagLocationEnd - tagContentsLocation})};
  499. Component comp;
  500. if (!tagContents.empty() && tagContents[0] == '=') {
  501. if (!parseSetDelimiterTag(tagContents, ctx.delimiterSet)) {
  502. streamstring ss;
  503. ss << "Invalid set delimiter tag at " << tagLocationStart;
  504. errorMessage_.assign(ss.str());
  505. return;
  506. }
  507. currentDelimiterIsBrace = ctx.delimiterSet.isDefault();
  508. comp.tag.type = Tag::Type::SetDelimiter;
  509. comp.tag.delimiterSet.reset(new DelimiterSet(ctx.delimiterSet));
  510. }
  511. if (comp.tag.type != Tag::Type::SetDelimiter) {
  512. parseTagContents(tagIsUnescapedVar, tagContents, comp.tag);
  513. }
  514. comp.position = tagLocationStart;
  515. sections.back()->children.push_back(comp);
  516. // Start next search after this tag
  517. inputPosition = tagLocationEnd + currentTagDelimiterEndSize;
  518. // Push or pop sections
  519. if (comp.tag.isSectionBegin()) {
  520. sections.push_back(&sections.back()->children.back());
  521. sectionStarts.push_back(inputPosition);
  522. } else if (comp.tag.isSectionEnd()) {
  523. if (sections.size() == 1) {
  524. streamstring ss;
  525. ss << "Unopened section \"" << comp.tag.name << "\" at " << comp.position;
  526. errorMessage_.assign(ss.str());
  527. return;
  528. }
  529. sections.back()->tag.sectionText.reset(new StringType(input.substr(sectionStarts.back(), tagLocationStart - sectionStarts.back())));
  530. sections.pop_back();
  531. sectionStarts.pop_back();
  532. }
  533. }
  534. // Check for sections without an ending tag
  535. walk([this](Component& comp, int) -> WalkControl {
  536. if (!comp.tag.isSectionBegin()) {
  537. return WalkControl::Continue;
  538. }
  539. if (comp.children.empty() || !comp.children.back().tag.isSectionEnd() || comp.children.back().tag.name != comp.tag.name) {
  540. streamstring ss;
  541. ss << "Unclosed section \"" << comp.tag.name << "\" at " << comp.position;
  542. errorMessage_.assign(ss.str());
  543. return WalkControl::Stop;
  544. }
  545. comp.children.pop_back(); // remove now useless end section component
  546. return WalkControl::Continue;
  547. });
  548. if (!errorMessage_.empty()) {
  549. return;
  550. }
  551. }
  552. enum class WalkControl {
  553. Continue,
  554. Stop,
  555. Skip,
  556. };
  557. using WalkCallback = std::function<WalkControl(Component&, int)>;
  558. void walk(const WalkCallback& callback) const {
  559. walkChildren(callback, rootComponent_);
  560. }
  561. void walkChildren(const WalkCallback& callback, const Component& comp) const {
  562. for (auto childComp : comp.children) {
  563. if (walkComponent(callback, childComp) != WalkControl::Continue) {
  564. break;
  565. }
  566. }
  567. }
  568. WalkControl walkComponent(const WalkCallback& callback, Component& comp, int depth = 0) const {
  569. WalkControl control{callback(comp, depth)};
  570. if (control == WalkControl::Stop) {
  571. return control;
  572. } else if (control == WalkControl::Skip) {
  573. return WalkControl::Continue;
  574. }
  575. ++depth;
  576. for (auto childComp : comp.children) {
  577. control = walkComponent(callback, childComp, depth);
  578. if (control == WalkControl::Stop) {
  579. return control;
  580. } else if (control == WalkControl::Skip) {
  581. control = WalkControl::Continue;
  582. break;
  583. }
  584. }
  585. --depth;
  586. return control;
  587. }
  588. bool parseSetDelimiterTag(const StringType& contents, DelimiterSet& delimiterSet) {
  589. // Smallest legal tag is "=X X="
  590. if (contents.size() < 5) {
  591. return false;
  592. }
  593. if (contents.back() != '=') {
  594. return false;
  595. }
  596. const auto contentsSubstr = trim(contents.substr(1, contents.size() - 2));
  597. const auto spacepos = contentsSubstr.find(' ');
  598. if (spacepos == StringType::npos) {
  599. return false;
  600. }
  601. const auto nonspace = contentsSubstr.find_first_not_of(' ', spacepos + 1);
  602. if (nonspace == StringType::npos) {
  603. return false;
  604. }
  605. delimiterSet.begin = contentsSubstr.substr(0, spacepos);
  606. delimiterSet.end = contentsSubstr.substr(nonspace, contentsSubstr.size() - nonspace);
  607. return true;
  608. }
  609. void parseTagContents(bool isUnescapedVar, const StringType& contents, Tag& tag) {
  610. if (isUnescapedVar) {
  611. tag.type = Tag::Type::UnescapedVariable;
  612. tag.name = contents;
  613. } else if (contents.empty()) {
  614. tag.type = Tag::Type::Variable;
  615. tag.name.clear();
  616. } else {
  617. switch (static_cast<char>(contents.at(0))) {
  618. case '#':
  619. tag.type = Tag::Type::SectionBegin;
  620. break;
  621. case '^':
  622. tag.type = Tag::Type::SectionBeginInverted;
  623. break;
  624. case '/':
  625. tag.type = Tag::Type::SectionEnd;
  626. break;
  627. case '>':
  628. tag.type = Tag::Type::Partial;
  629. break;
  630. case '&':
  631. tag.type = Tag::Type::UnescapedVariable;
  632. break;
  633. case '!':
  634. tag.type = Tag::Type::Comment;
  635. break;
  636. default:
  637. tag.type = Tag::Type::Variable;
  638. break;
  639. }
  640. if (tag.type == Tag::Type::Variable) {
  641. tag.name = contents;
  642. } else {
  643. StringType name{contents};
  644. name.erase(name.begin());
  645. tag.name = trim(name);
  646. }
  647. }
  648. }
  649. void render(const RenderHandler& handler, Context& ctx) {
  650. walk([&handler, &ctx, this](Component& comp, int) -> WalkControl {
  651. return renderComponent(handler, ctx, comp);
  652. });
  653. }
  654. StringType render(Context& ctx) {
  655. std::basic_ostringstream<typename StringType::value_type> ss;
  656. render([&ss](const StringType& str) {
  657. ss << str;
  658. }, ctx);
  659. return ss.str();
  660. }
  661. WalkControl renderComponent(const RenderHandler& handler, Context& ctx, Component& comp) {
  662. if (comp.isText()) {
  663. handler(comp.text);
  664. return WalkControl::Continue;
  665. }
  666. const Tag& tag{comp.tag};
  667. const Data<StringType>* var = nullptr;
  668. switch (tag.type) {
  669. case Tag::Type::Variable:
  670. case Tag::Type::UnescapedVariable:
  671. if ((var = ctx.get(tag.name)) != nullptr) {
  672. if (!renderVariable(handler, var, ctx, tag.type == Tag::Type::Variable)) {
  673. return WalkControl::Stop;
  674. }
  675. }
  676. break;
  677. case Tag::Type::SectionBegin:
  678. if ((var = ctx.get(tag.name)) != nullptr) {
  679. if (var->isLambda()) {
  680. if (!renderLambda(handler, var, ctx, false, *comp.tag.sectionText, true)) {
  681. return WalkControl::Stop;
  682. }
  683. } else if (!var->isFalse() && !var->isEmptyList()) {
  684. renderSection(handler, ctx, comp, var);
  685. }
  686. }
  687. return WalkControl::Skip;
  688. case Tag::Type::SectionBeginInverted:
  689. if ((var = ctx.get(tag.name)) == nullptr || var->isFalse() || var->isEmptyList()) {
  690. renderSection(handler, ctx, comp, var);
  691. }
  692. return WalkControl::Skip;
  693. case Tag::Type::Partial:
  694. if ((var = ctx.get(tag.name)) != nullptr && var->isPartial()) {
  695. const auto partial = var->partial();
  696. Mustache tmpl{partial()};
  697. if (!tmpl.isValid()) {
  698. errorMessage_ = tmpl.errorMessage();
  699. } else {
  700. tmpl.render(handler, ctx);
  701. if (!tmpl.isValid()) {
  702. errorMessage_ = tmpl.errorMessage();
  703. }
  704. }
  705. if (!tmpl.isValid()) {
  706. return WalkControl::Stop;
  707. }
  708. }
  709. break;
  710. case Tag::Type::SetDelimiter:
  711. ctx.delimiterSet = *comp.tag.delimiterSet;
  712. break;
  713. default:
  714. break;
  715. }
  716. return WalkControl::Continue;
  717. }
  718. bool renderLambda(const RenderHandler& handler, const Data<StringType>* var, Context& ctx, bool escaped, const StringType& text, bool parseWithSameContext) {
  719. const auto lambdaResult = var->callLambda(text);
  720. if (!lambdaResult.isString()) {
  721. return true;
  722. }
  723. Mustache tmpl = parseWithSameContext ? Mustache{lambdaResult.stringValue(), ctx} : Mustache{lambdaResult.stringValue()};
  724. if (!tmpl.isValid()) {
  725. errorMessage_ = tmpl.errorMessage();
  726. } else {
  727. const StringType str{tmpl.render(ctx)};
  728. if (!tmpl.isValid()) {
  729. errorMessage_ = tmpl.errorMessage();
  730. } else {
  731. handler(escaped ? escape(str) : str);
  732. }
  733. }
  734. return tmpl.isValid();
  735. }
  736. bool renderVariable(const RenderHandler& handler, const Data<StringType>* var, Context& ctx, bool escaped) {
  737. if (var->isString()) {
  738. const auto varstr = var->stringValue();
  739. handler(escaped ? escape(varstr) : varstr);
  740. } else if (var->isLambda()) {
  741. return renderLambda(handler, var, ctx, escaped, {}, false);
  742. }
  743. return true;
  744. }
  745. void renderSection(const RenderHandler& handler, Context& ctx, Component& incomp, const Data<StringType>* var) {
  746. const auto callback = [&handler, &ctx, this](Component& comp, int) -> WalkControl {
  747. return renderComponent(handler, ctx, comp);
  748. };
  749. if (var && var->isNonEmptyList()) {
  750. for (const auto& item : var->list()) {
  751. const ContextPusher ctxpusher{ctx, &item};
  752. walkChildren(callback, incomp);
  753. }
  754. } else if (var && var->isObject()) {
  755. const ContextPusher ctxpusher{ctx, var};
  756. walkChildren(callback, incomp);
  757. } else {
  758. walkChildren(callback, incomp);
  759. }
  760. }
  761. private:
  762. StringType errorMessage_;
  763. Component rootComponent_;
  764. };
  765. } // namespace
  766. #endif // MUSTACHE_HPP