3

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 ?

Julien Tanay
  • 964
  • 2
  • 11
  • 20

2 Answers2

2

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

from jinja2 import contextfilter, Template
from markupsafe import Markup


@contextfilter
def dangerous_render(context, value):
    return Markup(Template(value).render(context)).render()

Then in your template.html file:

{{ myvar|dangerous_render }}
Alan Hamlett
  • 3,038
  • 1
  • 22
  • 22
2

I was looking for a similar eval use case and bumped into a different stack overflow post.

This worked for me

routes.py

def index():
    html = "<b>actual eval string</b>"
    return render_template('index.html', html_str = html)

index.html

<html>
    <head>
        <title>eval jinja</title>
    </head>
    <body>
        {{ html_str | safe }}
    </body>
</html>

Reference : Passing HTML to template using Flask/Jinja2

Naveen Vijay
  • 15,196
  • 5
  • 68
  • 87