Reputation: 3097
lets say i am passing a variable "subtotal" inside a template using ..
in my views.py
subtotal = 0
page_vars = Context({
'players': players,
'subtotal': subtotal,
})
in my html.
{% for player in players %}
{% subtotal += player.score %}
{{ player.name }} <td />
{{ player.score }} <td />
{% endfor %}
{{ subtotal }}
it gives me
Invalid block tag: 'subtotal', expected 'empty' or 'endfor'
can't we have nested block tags in django templating system?
if yes, how?
there must be, as for me to calculate subtotal, i would have to calulate my subtotal, i have to run the same for loop at two places, which makes it highly ineffecient!
//mouse.
Upvotes: 0
Views: 255
Reputation: 2561
I would really advise that you retain separation of logic and display of information. The Django template system is purposely designed to minimize your ability to shoot yourself in the foot by gumming up your templates with logic and calculations.
Perform your calculations and logical manipulation in the view, and pass the finished product to the template. The template language is there to help you maintain code reusability and "debuggability" by attempting to enforce this separation of responsibility.
Upvotes: 0
Reputation: 174624
You can have nested tags:
{% for foo in bar %}
{% for zoo in foo %}
{% endfor %}
{% endfor %}
To add something, you need the add
template filter.
{{ player.score|add:subtotal }}
However, your problem needs to be resolved in the view. Since even with custom tags you cannot reliably keep track of a running total of a single variable in the template.
See this answer for an implementation to get you started, but note that they are talking about summing a list.
This kind of logic should be done in the view.
Upvotes: 1