0

The following code displays different values of x in different months. Set command of jinja2 works for flag,x but not for total. Why?

    {% set flag = 1 %}
    {% set total = 0 %}
    {% for date in dates %} //dates is some array
        {% if flag == 1 %}
            {{x}}
            {% set flag= 0 %} // I have used 1+1 also that too works
        {% elif "Jul" in date %}
            {% set x = x*3 %}
            {% if x % 10!=0 %}
                {% set x = x - x % 10 %}
                {% set total = total + x %}
            {% endif %}
        {% else %}
            {{x}}
            {% set total = total + x %}
        {% endif %}
    {% endfor %}
    {{total}}
  • Is the problem that final `{{total}}` outputs 0? If so, it is because assignments inside for-loop doesn't affects on variables outisde that loop. See also that question http://stackoverflow.com/questions/14726396/jinja-template-variable-assignment-scope – Tsyvarev Jul 08 '15 at 10:56
  • See [this question](http://stackoverflow.com/questions/4870346/can-a-jinja-variables-scope-extend-beyond-in-an-inner-block) too. – doru Jul 08 '15 at 11:14
  • Flag is also inside for loop and it runs only once and its value changes to 0 then why is it different for total? – Tarun Trikha Jul 08 '15 at 11:14
  • If I add {{flag}} after total it prints 0 and not 1. So either both flag and total should work or neither should work. I cannot understand. Please help!! – Tarun Trikha Jul 08 '15 at 12:48
  • What value has `x`? Are you sure is not 0? – doru Jul 08 '15 at 13:25
  • Yes its working perfectly fine. I can show you the original code but its too lengthy. – Tarun Trikha Jul 08 '15 at 15:21

1 Answers1

0

You have too complex computational logic in the template: it is better to move that logic(or its part) into data-provider component.

For example, in the data-provider component you can compute x for every data and place result into data.x. Then {{dates|sum(attribute='x')}} will display total value.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • I think this will work can u provide any link that can elaborate how to use the following concept before I mark ur answer as chosen. plz – Tarun Trikha Jul 09 '15 at 15:43
  • @TarunTrikha: About `sum` filter you can read its description at http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-filters. As for "template should contain minimum logic" concept - it is common concept for most template engines. See, e.g. this FAQ: http://jinja.pocoo.org/docs/dev/faq/#isn-t-it-a-terrible-idea-to-put-logic-into-templates. – Tsyvarev Jul 09 '15 at 16:31