8000 TemplateEnv Globals are removed after a call to Render · Issue #235 · jinja2cpp/Jinja2Cpp · GitHub
[go: up one dir, main page]

Skip to content
TemplateEnv Globals are removed after a call to Render #235
@sdegrande

Description

@sdegrande

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

#include <iostream>
#include <map>
#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:

Hello foo!!!
Hello !!!

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 <iostream>
#include <map>
#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!!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0