Yannick
Yannick

Reputation: 3663

Django how to DRY code from view

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

Answers (3)

Daniel Roseman
Daniel Roseman

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

Unapiedra
Unapiedra

Reputation: 16217

Depends on what is repeating.

  1. You can nest templates. Probably not useful here.
  2. You can write your own template tags and template filters. further info

Upvotes: 1

alecxe
alecxe

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

Related Questions