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:

  1. create list value of counter.
  2. use set _ = ... perform action have no effect on template (just setting varibale _ none nothing in context @ least decide need variable called _).
  3. use combination append/pop change value of counter (this works in jinja since allows calling functions on variables on set statement)
  4. use value in list whenever need value of counter.

and if wonder output of previous code here comes:

4 

hope helps.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -