Reputation: 185
I am trying to use the Django template to loop over a set of records, but stop one short, and then process the last one differently. So lets say I have 50 records - I would want to loop over 1 to 49 and then stop, and then process the 50th outside the loop. I am trying to create
[[date, var2],[date, var2],..[date, var2]*];
I am using:
data.addRows([
{% for data in mydata %}
[{{data.date}},{{data.var2}}],
{% endfor %}
]);
My aim is to NOT include the comma (indicated by the *) but to keep the required form. Any help would be appreciated. Thanks.
Upvotes: 2
Views: 51
Reputation: 53744
What you are looking for is forloop.last that makes it possible to do this task entirely within the loop.
data.addRows([
{% for data in mydata %}
{% if forloop.last %}
[{{data.date}},{{data.var2}}]
{% else %}
[{{data.date}},{{data.var2}}],
{% endif %}
{% endfor %}
]);
There is an alternative, the last filter which returns the last item on a list, but the above method is the more conventional way of doing this.
Upvotes: 1