Reputation: 3663
I'm just starting coding in Django and I have code that repeat itself on a lot of pages.
for example:
<select name="seasons" id="season-id">
{% for season in seasons %}
{% if season_id|add:0 == season.id %}
<option value="{{ season.id }}" selected="selected">{{ season.name }}</option>
{% else %}
<option value="{{ season.id }}">{{ season.name }}</option>
{% endif %}
{% endfor %}
</select>
In previous language I could use view helpers to make it more DRY. How can I accomplish this in Django.
Upvotes: 0
Views: 156
Reputation: 599856
You shouldn't be writing this template code at all. You should define a Django form and let that output the field.
Upvotes: 0
Reputation: 16217
Depends on what is repeating.
Upvotes: 1
Reputation: 474081
Extract the code into a separate template file and include
it instead of repeating:
{% include "seasons.html" %}
FYI, you can also specify that you want to pass only seasons
variable into the context of included template:
{% include "seasons.html" with seasons=seasons only %}
Upvotes: 2