Excesses Variable Outside The loop in jinja

{% set total_g_weight = 0 %}
{% for i in doc.items %}
{% set g_weight = i.qty|float * i.custom_gross_weight|float %}

<!-- Add g_weight to the total -->
{% set total_g_weight = total_g_weight + g_weight %}

<!-- Display g_weight for the current item -->
<td style='text-align:right;'><b>{{ "%.4f €"|format(g_weight) }}</b></td>

{% endfor %}

Total Gross Weight : {{ "%.4f €"|format(total_g_weight) }}

I think, the variable total_g_weight does not retain its updated value inside the loop because of Jinja’s scoping rules. To accumulate the value properly, you can use a different approach by leveraging a more suitable method, such as utilizing a loop with an external list or dictionary for accumulation

try this

{% set g_weights = [] %}  
{% for i in doc.items %}
    {% set g_weight = i.qty | float * i.custom_gross_weight | float %}
    {% do g_weights.append(g_weight) %} 

    <!-- Display g_weight for the current item -->
    <td style='text-align:right;'><b>{{ "%.4f €"|format(g_weight) }}</b></td>
{% endfor %}

{% set total_g_weight = g_weights | sum %}
<!-- Display the total gross weight after the loop -->
Total Gross Weight : <b>{{ "%.4f €"|format(total_g_weight) }}</b>
1 Like

@gopikrishnan , You have to use namespace . Sample Code as hereunder

 {% set grand_total =namespace(total=0) %}

{% for row in doc.items %}
{% set row_total = (row.qty|float) * (row.cost_for_print|float) %}

{% set grand_total.total = grand_total.total + row_total %}
{% endfor %}

Merchandise Total: {{ grand_total.total }}
1 Like

{% set total_g_weight = {‘value’: 0, ‘ctn’: 0} %}
{% for i in doc.items %}
{% set total_g_weight = {
‘ctn’: total_g_weight[‘ctn’] + i.custom_ctn,
‘value’: total_g_weight[‘value’] + (i.qty|float * i.custom_gross_weight|float)
} %}
{% endfor %}
this also working

1 Like

@ErpnextRaja Cool, actually I’m not a Jinja template expert, but I do have some basic knowledge of it. Thanks for the info though, I learned something new!

1 Like