2

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?

A. Innokentiev
  • 681
  • 2
  • 11
  • 27
  • Possible duplicate of [Django template conditional variable assignment](http://stackoverflow.com/questions/10786214/django-template-conditional-variable-assignment) – Leistungsabfall Mar 26 '16 at 17:21
  • Also see [Django Template Ternary Operator](http://stackoverflow.com/questions/3110166/django-template-ternary-operator). – alecxe Mar 26 '16 at 17:25

1 Answers1

3

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.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94