Try ERPNext Try Frappe Cloud Buy Support Partners Foundation

[Tutorial] Jinja How To : Add and update dictionary for grouping

Other way : You can use below code to add and update dictionary for grouping and summing up value:

{% 
set items = [
{'item_code':'item1', 'qty': 100, 'amount': 1000},
{'item_code':'item2', 'qty': 200, 'amount': 2000},
{'item_code':'item1', 'qty': 100, 'amount': 1000},
{'item_code':'item3', 'qty': 300, 'amount': 3000},
{'item_code':'item2', 'qty': 200, 'amount': 2000},
]

%}

{%- set item_group= dict() -%}
{%- for item in items -%}
	{%- set qty = item.qty + item_group.get(item.item_code, {}).get("qty", 0)  -%}
	{%- set amount = item.amount + item_group.get(item.item_code, {}).get("amount", 0)  -%}
	{% set _ = item_group.update({item.item_code: {"qty":qty, "amount":amount}} ) %}
{%- endfor -%}

<table>
<thead>
	<tr>
		<th>Item Code</th>
		<th>Qty</th>
		<th>Amount</th>
	</tr>
</thead>
<tbody>
{% set total=namespace(qty=0, amount=0) %}
{% for item_code, item in item_group|dictsort %}
	<tr>
		<td>{{ item_code }}</td>
		<td>{{ item.qty }}</td>
		<td>{{ item.amount}}</td>
	</tr>
{% set total.qty=total.qty + item.qty %}
{% set total.amount = total.amount + item.amount %}

{% endfor %}
</tbody>
<tfoot>
	<tr>
		<th>Grand Total</th>
		<th>{{ total.qty }}</th>
		<th>{{ total.amount }}</th>
	</tr>
</tfoot>
</table>
1 Like