Tech News
← Back to articles

String Interpolation in C++ Using Glaze Stencil/Mustache

read original related products more articles

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.

Basic Usage¶

struct person { std :: string first_name {}; std :: string last_name {}; uint32_t age {}; bool hungry {}; bool employed {}; }; // Basic interpolation std :: string_view layout = R " ( {{first_name}} {{last_name}} is {{age}} years old ) " ; person p { "Henry" , "Foster" , 34 }; auto result = glz :: stencil ( layout , p ); // Result: "Henry Foster is 34 years old"

[!NOTE] result in these examples is a std::expected . 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 .

Template Syntax Specification¶

Variable Interpolation¶

{{key}} - Replaces with the value of the specified field from the struct

- Replaces with the value of the specified field from the struct {{{key}}} - Triple braces for unescaped output (mustache format only)

Boolean Sections¶

{{#boolean_key}} CONTENT {{/boolean_key}} - Shows CONTENT if the boolean field is true

... continue reading