Search code examples
pythonsmartyjinja2

"eval" statement in Jinja2 template


I'm trying to convert some old Smarty templates to Jinja2.

Smarty uses an eval statement in the templates to render a templated string from the current context.

Is there an eval equivalent in Jinja2 ? Or what is a good workaround for this case ?


Solution

  • Use the @jinja2.contextfilter decorator to make a Custom Filter for rendering variables:

    from flask import render_template_string
    from jinja2 import contextfilter
    from markupsafe import Markup
    
    
    @contextfilter
    def dangerous_render(context, value):
        Markup(render_template_string(value, **context)).format()
    

    Then in your template.html file:

    {{ myvar|dangerous_render }}