How to dynamically add items to jinja variable in Flask? How to dynamically add items to jinja variable in Flask? flask flask

How to dynamically add items to jinja variable in Flask?


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 adddo 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).


To complete the answer of Slava Bacherikov, if you don't have the Jinja "do extension", you can use the tag set:

{% if g.user.is_authenticated() %}    {# use a dummy variable name, we juste need the side-effect of method call #}    {% set _z = navigation_bar.append(('/someotherpage', 'someotherpage', 'SomeOtherPage')) %}{% endif %}