pongo2 icon indicating copy to clipboard operation
pongo2 copied to clipboard

exec tag added to enable treating evaluated string as a part of the t…

Open sprksh opened this issue 3 years ago • 3 comments

Description of the change

Idea is to provide users a functionality so that by using {% exec %} templatetag, they can evaluate a string-based template (say passed as an argument) as a part of the original template.

For example, user can define a macro in a string and use that in the same execution flow.

Our use case was that the user can define macros in yaml and then call it from the yaml itself and we should be able to treat the macro as one of the predefined macros. Earlier we were doing two step evaluation but that limited the capability of the system.

We could not define this templateTag from outside as it has to use few variables private to the package.

func test() {
	tpl, err := pongo2.FromFile("some_file.template")
	if err != nil {
		log.Fatal(err)
	}

	c1 := `{% macro double(arg) %}{{2*arg}}{% endmacro %}`
	c2 := "{{ double(10) }}"
	res, err := tpl.Execute(pongo2.Context{"c1": c1, "c2": c2})
	if err != nil {
		log.Fatal(err)
	}

}

some_file.template

{% exec %}{{c1}}{% endexec %}
{% exec %}{{c2}}{% endexec %}

so effectively this file will be evaluated as

{% macro double(arg) %}{{2*arg}}{% endmacro %}
{{ double(10) }}

and the result will be


20

sprksh avatar Sep 21 '22 12:09 sprksh

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
No Duplication information No Duplication information

sonarqubecloud[bot] avatar Sep 21 '22 12:09 sonarqubecloud[bot]

@flosch please let me know your thoughts about the added functionality :)

sprksh avatar Sep 26 '22 09:09 sprksh