我在Jinja2中有一个自定义标签,我想在第一次调用时输出一些东西.所以说我有以下模板:
1. {% only_once %}
2. {% only_once %}
3. {% only_once %}
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
1. "I only get printed once!"
2.
3.
Run Code Online (Sandbox Code Playgroud)
我猜测最好的方法是在模板的上下文中设置一个标志来跟踪我是否已经打印过一些东西.这是一个代码示例,但这是对的吗?
class OnlyOnceExtension(Extension):
tags = set(['only_once'])
@contextfunction
def parse(self, context, parser):
if hasattr(context, 'my_flag') and context.my_flag:
return Output("")
else:
return Output("I only get printed once!")
Run Code Online (Sandbox Code Playgroud)
那是对的吗?我读了一些关于上下文的东西是不可变的,所以这不起作用吗?(参见http://jinja.pocoo.org/2/documentation/api并搜索immutable)
如果你想纯粹使用Jinja,你可以用这种方式检查loop.index变量,
{% for bar in bars %}
{% if loop.index == 1 %}
Print me once
{% endif %}
Print me every time
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1461 次 |
| 最近记录: |