flosch / pongo2

Django-syntax like template-engine for Go
https://www.schlachter.tech/pongo2
MIT License
2.86k stars 269 forks source link

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

Closed sprksh closed 1 year ago

sprksh commented 1 year ago

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 string and use that in the same execution flow.

Our use case was that 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 := Po.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 %}{{c1}}{% endexec %}

so effectively this file will be evaluated as

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

and the result will be


20
sonarcloud[bot] commented 1 year ago

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
0.0% 0.0% Duplication