python ternary in jinja2 gives TemplateSyntaxError: tag name expected

*爱你&永不变心* 提交于 2021-02-05 02:29:36

问题


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 :)


回答1:


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



回答2:


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 %}" >


来源:https://stackoverflow.com/questions/35914673/python-ternary-in-jinja2-gives-templatesyntaxerror-tag-name-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!