Reputation: 375
I am sending one list of list to my HTML page, using flask jinja2 template. I want to check:- is item in list is of type str or not ?. But getting an exception of
jinja2.exceptions.UndefinedError: 'isinstance' is undefined
Code is as below:-
{% for i in req%}
<tr>
<th scope="row">{{loop.index}}</th>
<td>{{i[1]}}</td>
<td>{{i[24]}}</td>
<td>{{i[49]}}</td>
<td>{{i[53]}}</td>
{% if isinstance(i[86], str) %}
{% for j in i[86].split(",") %}
<ol>
<li>{{i[86]}}</li>
</ol>
{% endfor %}
{% else %}
<td>{{i[86]}}</td>
{% endif %}
</tr>
{% endfor %}
I am able to use split(",")
function and Want to use isinstance()
or str()
of python in jinja 2 template.
Upvotes: 5
Views: 2295
Reputation: 11912
Another option is using a Flask context processor. For example, from the Flask docs, here is a context processor that makes a format_price
function available in all templates in the application:
app = Flask(__name__)
@app.context_processor
def utility_processor():
def format_price(amount, currency="€"):
return f"{amount:.2f}{currency}"
return dict(format_price=format_price)
The idea is that you decorate a function with @app.context_processor
and then the dictionary it returns in automagically merged into the Jinja context for all templates.
Note that this can even be used to add entire modules to the template context.
Upvotes: 0
Reputation: 5048
The language in the jinja template is not actually python, it's python like looking, it means python built-ins are not present. To make python built-ins present in every template, at startup, add any required built-ins to the globals
parameter when building the jinja2.Environment
. Something like below:
app.jinja_env.globals.update(isinstance=isinstance)
or
import jinja2
env = jinja2.Environment()
env.globals.update(isinstance:isinstance)
Upvotes: 6