Crow/docs/guides/templating.md
The-EDev 8523afa930 Update templating.md and mustache.h
Updated templating documentation to mention "working directory" rather than "executable directory".
Added Warning log when a template is not found.
2021-02-09 06:52:05 +03:00

1.5 KiB

Templating is when you return an html page with custom data. You can probably tell why that's useful.

Crow supports mustache for templates through its own implementation crow::mustache.

##Components of mustache

There are 2 components of a mustache template implementation:

  • Page
  • Context

###Page The HTML page (including the mustache tags). It is usually loaded into crow::mustache::template_t. It needs to be placed in the templates directory which should be directly inside the current working directory of the crow executable.

For more information on how to formulate a template, see this mustache manual.

###Context A JSON object containing the tags as keys and their values. crow::mustache::context is actually a crow::json::wvalue.

##Returning a template To return a mustache template, you need to load a page using #!cpp auto page = crow::mustache::load("path/to/template.html");, keep in mind that the path is relative to the templates directory.
You also need to set up the context by using #!cpp crow::mustache::context ctx;. Then you need to assign the keys and values, this can be done the same way you assign values to a json write value (ctx["key"] = value;).
With your context and page ready, just #!cpp return page.render(ctx);. This will use the context data to return a filled template.
Alternatively you could just render the page without a context using #!cpp return page.render();.