Jinja variable scope problem

Hi Team,

I researched and found there is a problem with scope of variable outside loop. But hope there will be a solution for this.

I am trying to calculate total value of a column, if printing inside loop its coming correct. But while printing outside, it’s printing zero again.

How to solve this problem?

Writing a code like this (it’s part of complete code)…

{% set count = 0 %}
{%- for row in doc.items -%}
{% set wt = row.net_wt | float %}
{% set qty = row.qty | float %}
{% set net_wt = wt*qty %}
{% set grs_wt = net_wt+1.4 %}
{% set count = count+grs_wt %}

{{ row.ctn_no }}
{{ row.description}}
{{ row.style_no}}
{{ row.article_no}}
{{ row.po_size}}
{{ row.po_color}}
{{ row.qty }}
{{ row.qty }}
{{count}} <!-- increased correct value —>
{{ row.qty }}
{{ net_wt }}
{%- endfor -%}

{{count}} <!-- value zero—>

1 Like

Try setting doc.count instead of count.

On a general note, Jinja is not optimized for logic, you should set the values, maybe in a custom script and use Jinja for templating.

No it’s not solving the problem.
Can you please help me in understanding how to enable the “do” expression-statement extension, if you ever came across this?

Solutions may be this :
I found this at templates - Can a Jinja variable's scope extend beyond in an inner block? - Stack Overflow

One way around this limitation is to enable the “do” expression-statement extension and use an array instead of boolean:

{% set exists = [] %}
{% for i in range(5) %}
      {% if True %}
          {% do exists.append(1) %}
      {% endif %}
{% endfor %}
{% if exists %}
    <!-- exists is true -->
{% endif %}

To enable Jinja’s “do” expression-statement extension: e = jinja2.Environment(extensions=[“jinja2.ext.do”,])

If any how we may solve this problem, then we can customize our print format as we want.

May be we can add the extension here:

If you want to send a pull-request for this, we can merge, or create a GitHub Issue.