开发者

Creating Jinja variables/filters similar to loop.cycle()

I'm trying to create a custom Jinja variable that will cycl开发者_运维技巧e through a list of values each time it is used. This is similar to loop.cycle('a','b','c'), except that I'm not inside a for loop.

Example:

list = ['val1','val2','val3']  
{{ list|next }}  
{{ list|next }}  
{{ list|next }}  
{{ list|next }}  

Output:

val1  
val2  
val3  
val1  


Jinja2, since v2.1, allows loop unbound cycling, as the documentation shows.

In your example, you would do something like this:

{% set cycling_list = cycler('val1', 'val2', 'val3') %}
{{ cycling_list.next() }}  
{{ cycling_list.next() }}  
{{ cycling_list.next() }}

There's also cycler.reset, and cycler.current.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜