String Interpolation in C++ Using Glaze Stencil/Mustache
4 months ago
9
Glaze provides string interpolation for C++ structs through the stencil and mustache formats. These provide templating mechanisms for formatting structured data into strings, inspired by the Mustache templating language. This enables the generation of dynamic output by combining predefined templates with C++ structs.
structperson{std::stringfirst_name{};std::stringlast_name{};uint32_tage{};boolhungry{};boolemployed{};};// Basic interpolationstd::string_viewlayout=R"({{first_name}} {{last_name}} is {{age}} years old)";personp{"Henry","Foster",34};autoresult=glz::stencil(layout,p);// Result: "Henry Foster is 34 years old"
[!NOTE]
result in these examples is a std::expected<std::string, glz::error_ctx>. Like most functions in Glaze (e.g. glz::write_json) you can also pass in your own string buffer as the last argument, in which case the return type is glz::error_ctx.
std::string_viewlayout=R"({{first_name}} {{last_name}} {{^hungry}}I'm not hungry{{/hungry}})";personp{"Henry","Foster",34,false};// hungry is falseautoresult=glz::stencil(layout,p);// Result: "Henry Foster I'm not hungry"
std::string_viewlayout=R"({{title}}{{^items}} - No items found{{/items}})";TodoListempty_list{"Empty List",{},false};autoresult=glz::stencil(layout,empty_list);// Result: "Empty List - No items found"
Use glz::format_error like the rest of Glaze to generate a nicely formatted error with context. Note that rather than passing the buffer into the formatter, pass in the layout/template string.