我在Jinja2中有一個自定義標記,我只想在第一次調用時輸出一些東西。所以說,我有以下的模板:如何確保Jinja自定義標籤只輸出一次?
1. {% only_once %}
2. {% only_once %}
3. {% only_once %}
我所要的輸出是:
1. "I only get printed once!"
2.
3.
我猜做到這一點的最好的辦法是設置一個標誌,在模板的上下文跟蹤我是否已經打印了某些東西。這是一個代碼示例,但是這是正確的嗎?
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!")
這是正確的嗎?我讀了一些關於上下文的東西是不可變的,所以這不起作用? (見http://jinja.pocoo.org/2/documentation/api和搜索不可變)
我試圖用這個宏,但它不是有效的代碼,'TemplateSyntaxError:預計令牌'打印聲明結束',得到'was_printed' ' – topless 2012-12-19 11:18:13