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.
精彩评论