A. Innokentiev
A. Innokentiev

Reputation: 721

How to choose or assign variable in django template?

I have an template:

{% if c == 2 %}
    {% for time in a %}
        code(1)
    {% endfor %}
{% else %}
    {% for time in b %}
        repeat of code(1)
    {% endfor %}
{% endif %}

As you can see this code has an repeating part. I want to refactor like this:

{% if c == 2 %}
    var = a
{% else %}
    var = b
{% endif %}
{% for time in var %}
    code(1)
{% endfor %}

How to do this?

Upvotes: 2

Views: 2089

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

Don't do that in the template(and I don't think you can), do that in views.py instead:

var = c if c == 2 else b
# add to template context
context['var'] = var

If you add too much logic in template, people have to look at both places to figure out what's going on. But if you have all the logics in views.py it's clearer.

Upvotes: 3

Related Questions