我使用Flask使用jinja2 templating engine构建网站,并且我动态构建菜单(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>
现在,如果用户已登录,我想展示一些其他内容。所以在运行时我想将项添加到navigation_bar变量。我试过这样的事情:
{% if g.user.is_authenticated() %}
{% navigation_bar.append(('/someotherpage', 'someotherpage', 'SomeOtherPage')) -%}
{% endif %}
但不幸的是,这会导致以下错误:TemplateSyntaxError: Encountered unknown tag 'navigation_bar'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
那么:有人知道如何在运行时向jinja2变量中添加其他项吗?欢迎所有提示!
[红利问题]
我也想知道-
在{% set active_page = active_page|default('index') -%}
结束时做了什么?
答案 0 :(得分:5)
发生错误是因为Jinja无法识别阻止。每个Jinja块应该从块名称开始。来自do extension的do
屏障符合您的需求。要使用它,你应该添加
做扩展到jinja扩展。你可以这样做:
app.jinja_env.add_extension('jinja2.ext.do')
然后你可以使用do扩展。您的示例应如下所示:
{% if g.user.is_authenticated() %}
{% do navigation_bar.append(('/someotherpage', 'someotherpage', 'SomeOtherPage')) %}
{% endif %}
Here's另一个简单的例子。
您将找到红利问题的答案 here。简而言之,-
会从块的开头或结尾删除空格(这取决于它所在的位置)。
答案 1 :(得分:0)
要完成answer of Slava Bacherikov,如果您没有 Jinja“do extension”,您可以使用标签 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 %}