TemplateEnv Globals are removed after a call to Render (original) (raw)

Here is a small example which fails to run as expected:

#include #include #include <jinja2cpp/template.h> #include <jinja2cpp/template_env.h>

int main(int argc, char *argv[]) { jinja2::TemplateEnv tplEnv; tplEnv.AddGlobal("global_var", jinja2::Value("foo")); { jinja2::Template tpl(&tplEnv); tpl.Load("Hello {{ global_var }}!!!"); std::string result = tpl.RenderAsString(jinja2::ValuesMap{}).value(); std::cout << result << std::endl; } { jinja2::Template tpl(&tplEnv); tpl.Load("Hello {{ global_var }}!!!"); std::string result = tpl.RenderAsString(jinja2::ValuesMap{}).value(); std::cout << result << std::endl; } return 0; }

The output is:

I displayed the content of the Globals before and after the first rendering, using that code:

tplEnv.ApplyGlobals([](jinja2::ValuesMap &map) { for (const auto& [key, val] : map) { std::cout << "-> tplenv " << key << " " << val.asString() << std::endl; } });

Here is the result:

-> tplenv global_var foo
Hello foo!!!
-> tplenv global_var
Hello !!!

So, something is removing the content of the global vars, which is annoying because currently it means that globals have to be "reloaded" before a call to Render...

Note that MakeCallable globals are still present and working after a call to Render:

#include #include #include <jinja2cpp/template.h> #include <jinja2cpp/template_env.h> #include <jinja2cpp/user_callable.h>

int main(int argc, char *argv[]) { jinja2::TemplateEnv tplEnv; tplEnv.AddGlobal("global_var", jinja2::Value("foo")); tplEnv.AddGlobal("global_fn", jinja2::MakeCallable( { return "bar"; })); { jinja2::Template tpl(&tplEnv); tpl.Load("Hello {{ global_var }} {{ global_fn() }}!!!"); std::string result = tpl.RenderAsString(jinja2::ValuesMap{}).value(); std::cout << result << std::endl; } { jinja2::Template tpl(&tplEnv); tpl.Load("Hello {{ global_var }} {{ global_fn() }}!!!"); std::string result = tpl.RenderAsString(jinja2::ValuesMap{}).value(); std::cout << result << std::endl; } return 0; }

returns:

Hello foo bar!!!
Hello  bar!!!