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