Shiva Shiva - 3 years ago 303
Python Question

jinja2: TemplateSyntaxError: expected token ',', got 'string'

I am new to Jinja2 and having an issue with using python regular expression (re). In the following code I would like to bold the lines that have error string in them.

{% block content %}
<div class="container">
{% for l in lines %}
{% if re.search(r"Error", l) %} {# <<< Throws error #}
<b> {{ l }} </b>
{% else %}
{{ l }} <hr>
{% endif %}
{% endfor %}
</div>
{% endblock %}


The re.search above throws following error:

jinja2.exceptions.TemplateSyntaxError
TemplateSyntaxError: expected token ',', got 'string'

Answer Source

Raw python code is not fully supported in jinja2 template syntax.

{% if re.search(r"Error", l) %}

replace this line with

{% if "Error" in l %}

can fix your problem.

if your logical condition is more complicated, you should consider defining your own custom filters(which can call any python code) or do the complicated things in your view layer. also go check global namespace.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download