Jinja variable scope or how can I access integer which have been incremented inside loop? -
i have following jinja template:
{% set counter = 0 %} {% f in somearray %} {% set counter = counter + 123 %} {% endfor %} // here want print {{counter}}, 0.
i looked @ answer can jinja variable's scope extend beyond in inner block? did not help. tried create array variable , access it
{% set counter = 0 %} {% set sz = [0] %} {% f in somearray %} {% set counter = counter + 123 %} {% set sz[0] = counter %} <---- crash here {% endfor %}
jinja documentation says nothing array access... please help.
to use array counter need modify code (and hacks!) show way of doing want without extensions.
ok, main problem in code when set
variable on jinja statement keeps value in scope (is local variable definition on function in python) , since jinja doesn't provide strightforward way of setting outside variables created on template need hacks. magic works using list:
import jinja2 env = jinja2.environment() print env.from_string(""" {%- set counter = [0] -%} {%- f in somearray -%} {%- set _ = counter.append(counter.pop()+1) -%} {%- endfor -%} {{counter[0]}} """).render(somearray=[1,2,3,4])
steps:
- create list value of counter.
- use
set _ = ...
perform action have no effect on template (just setting varibale_
none
nothing in context @ least decide need variable called_
). - use combination
append
/pop
change value of counter (this works in jinja since allows calling functions on variables on set statement) - use value in list whenever need value of counter.
and if wonder output of previous code here comes:
4
hope helps.
Comments
Post a Comment