pacdev
August 28, 2015, 5:10am
1
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 }}
{{grs_wt}}
{%- endfor -%}
TOTAL QTY
{{count}} <!-- value zero—>
1 Like
rmehta
August 28, 2015, 4:04pm
2
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.
pacdev
August 28, 2015, 6:20pm
3
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”,])
pacdev
August 28, 2015, 6:32pm
4
If any how we may solve this problem, then we can customize our print format as we want.
rmehta
September 1, 2015, 4:11am
5
May be we can add the extension here:
# License: MIT. See LICENSE
def get_jenv():
import frappe
from frappe.utils.safe_exec import get_safe_globals
if not getattr(frappe.local, "jenv", None):
from jinja2 import DebugUndefined
from jinja2.sandbox import SandboxedEnvironment
# frappe will be loaded last, so app templates will get precedence
jenv = SandboxedEnvironment(loader=get_jloader(), undefined=DebugUndefined)
set_filters(jenv)
jenv.globals.update(get_safe_globals())
methods, filters = get_jinja_hooks()
jenv.globals.update(methods or {})
jenv.filters.update(filters or {})
frappe.local.jenv = jenv
If you want to send a pull-request for this, we can merge, or create a GitHub Issue.