简体   繁体   中英

How to dynamically add items to jinja variable in Flask?

I'm building a website using Flask with its jinja2 templating engine and I'm dynamically building the menu ( as described here ):

{%
    set navigation_bar = [
        ('/', 'index', 'Home'),
        ('/aboutus/', 'aboutus', 'About Us'),
        ('/faq/', 'faq', 'FAQ')
    ]
%}

{% set active_page = active_page|default('index') -%}

<ul>
{% for href, id, title in navigation_bar %}
    <li{% if id == active_page %} class="active"{% endif %}>
        <a href="{{ href|e }}">{{ title|e }}</a>
    </li>
{% endfor %}
</ul>

Now if a user is logged in I want to show some additional things. So at runtime I want to add items to the navigation_bar variable. I tried something like this:

{% if g.user.is_authenticated() %}
    {% navigation_bar.append(('/someotherpage', 'someotherpage', 'SomeOtherPage')) -%}
{% endif %}

But unfortunately this results in the following error: TemplateSyntaxError: Encountered unknown tag 'navigation_bar'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'. TemplateSyntaxError: Encountered unknown tag 'navigation_bar'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

So: does anybody know how I can add additional items to a jinja2 variable at runtime? All tips are welcome!

[bonus question] I was also wondering, what does the - do at the end of {% set active_page = active_page|default('index') -%} ?

The error occurs because Jinja can't identify block. Each Jinja block should start from block name. do block from do extension meets your needs. To use it you should add do extension to jinja extensions. You can do this like so:

app.jinja_env.add_extension('jinja2.ext.do')

And then you can use do extension. Your example should looks like this:

{% if g.user.is_authenticated() %}
    {% do navigation_bar.append(('/someotherpage', 'someotherpage', 'SomeOtherPage')) %}
{% endif %}

Here's another simple example.

You will find answer to your bonus question here . In short - removes whitespaces from start or end of block (this depends on where it is located).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM