jamboree / bustache

C++20 implementation of {{ mustache }}
82 stars 10 forks source link

Is it possible to execute a function when a specific replacement tag is rendered? #28

Closed luz-arreola closed 1 year ago

luz-arreola commented 1 year ago

I currently use Bustache the normal way, I first load a json object with data that is mapped to replacement tags.

If no mapping is found, is it possible to execute a function when a certain replacement tag is encountered instead. This function would then provide the data to the replacement tag.

Let me explain why I ask. Assume that you have a replacement tag {{debugInformation}} that is expensive to compute. This tag is only inserted arbitrarily by the user (when the template is developed or modified).

This is not an enhancement request, if this is not possible, I can use arguments configuration options to either compute or not compute this debug information. Thank you.

jamboree commented 1 year ago

You can used the Unresolved Handler in Render API, e.g.

std::string replace;
const auto onUnresolved =
    [&replace](std::string const& key) -> bustache::value_ptr {
    replace = "<unresolved: " + key + ">";
    return &replace;
};

bustache::render_ostream(std::cout, format, obj, bustache::no_context_t{},
                         bustache::no_escape_t{}, onUnresolved);

Be sure that the lifetime of the return-value (i.e. replace in the example above) exceeds the function.