This has almost certainly been asked here before, so apologies if it’s a duplicate. I can’t find the answer though 🙂
In Django, in general, is it more efficient to do calculations in the view, or in the template?
Here’s a simple example. I want to put a particular string in the template, dependent on the value of an integer. I could do it in views.py:
# in views.py
description = "small"
if count > 10:
description = "large"
elif count > 5:
description = "medium"
Or I could do it this way in the template:
# in template.html
{{ count }}
({% if count > 10 %}large
{% else %}
{% if count > 5 %}medium{% else %}small{% endif %}
{% endif %})
In this case, the code is noticeably simpler in views, so perhaps that answers my question: but what I really want to know is, does it make a difference to efficiency to do it in either the template or the view?
It depends what you mean by efficient.
The former version involves fewer function calls, because when logic is contained in a template, the strings must first be parsed into nodes and tokenized, before being executed.
However, the performance of both of those will be identical in a real-world context, as they are both very simple.
A broader interpretation of efficiency would include the maintainability of code, which is generally more readable and more easy to refactor when contained in the view (or model, where appropriate).
In either interpretation, it’s best to move as much logic as possible out of the template and into view, controllers, or templatetags.