Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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 ?

like image 788
Julien Tanay Avatar asked Oct 16 '25 10:10

Julien Tanay


2 Answers

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 }}
like image 190
Alan Hamlett Avatar answered Oct 18 '25 23:10

Alan Hamlett


Based on the answers from Alan Hamlett and Hilario Nengare, I implemented the following "eval" filter for Jinja2 (>=3.0). I found that the case of undefined input should also be handled, plus I added the ability to specify additional variables as input for the expression:

import jinja2

@jinja2.pass_context
def filter_eval(context, input, **vars):
    if input == jinja2.Undefined:
        return input
    return jinja2.Template(input).render(context, **vars)

Usage, when adding filter_eval() as filter "eval":

  • Template source:

    {% set rack_str = 'Rack {{ rack }}' %}
    {{ rack_str | eval(rack='A') }}
    
  • Rendered template:

    Rack A
    
like image 35
Andreas Maier Avatar answered Oct 19 '25 00:10

Andreas Maier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!