Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ternary in jinja2 gives TemplateSyntaxError: tag name expected

I have a table and I want to change background color of tr if value of person.storyPublished is true otherwise do nothing.

My code looks like this:

 {% for person in people %}
    <tr class="row-person {% '.row-story-published' if  person.storyPublished  else ' ' %}" >
    <td>
    {{ person.name }}
    </td>
    ...

I get this error:

jinja2.exceptions.TemplateSyntaxError
TemplateSyntaxError: tag name expected

and the CSS part is here:

<style>
    .row-story-published{
        background-color: #b3ffb3;
    }
</style>

why is this happening? What i miss that I don't notice? Any help :)

like image 524
EgzEst Avatar asked Mar 10 '16 11:03

EgzEst


People also ask

What is Jinja tag?

Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher and is licensed under a BSD License. Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox.

Is Jinja2 part of Python?

Jinja2 is a feature rich templating language widely used in the Python ecosystem. It can be used directly in your Python programs and a lot of larger applications use it as their template rendering engine.

What is Jinja2 in flask?

Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present.


2 Answers

You used "{% %}" which wants to get a tag like if, endif etc. If you just want to execute a piece of python code, like your ternary expression, you should use double braces like so

{{ 'row-story-published' if  person.storyPublished  else ' ' }}
like image 168
René Jahn Avatar answered Sep 28 '22 11:09

René Jahn


Template language is different than Python, so has different syntax. You cannot use Python's idiomatic syntax in templates.

<tr class="row-person {% if  person.storyPublished %} row-story-published {% endif %}" >
like image 26
Muhammad Tahir Avatar answered Sep 28 '22 12:09

Muhammad Tahir