'if'语句内有多个Django'with'语句

时间:2019-11-04 08:53:32

标签: django templates django-templates

我在'if / elif'语句中有一个Django多个'with'语句。 除了一个变量“ slide1_line2”以外,if / elif内部的代码块相同。 我想知道是否有一种方法可以重写代码以避免重复。

{% if country == 'England' or country == 'Wales'%}              
{% with graphic='map.png' %}
{% with classes='color-1' %}
{% with slide1_line1='Your constituency is '|add:name %}
{% with slide1_line2='Heading1' %}
{% with slide1_line3='text' %}
{% with icon='keyboard_arrow_down' %}
{% include 'slide_map.html' %}
{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}

{% elif country == 'Scotland' or country == 'Northern Ireland' %}               
{% with graphic='map.png' %}
{% with classes='color-1' %}
{% with slide1_line1='Your constituency is '|add:name %}
{% with slide1_line2='Heading2' %}
{% with slide1_line3='text' %}
{% with icon='keyboard_arrow_down' %}
{% include 'slide_map.html' %}
{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}

{% endif %}

1 个答案:

答案 0 :(得分:1)

您可以排除if语句之外的公用值:

{% with graphic='map.png' classes='color-1' slide1_line1='Your constituency is '|add:name slide1_line3='text' icon='keyboard_arrow_down' %}
  {% if country == 'England' or country == 'Wales' %}
    {% include 'slide_map.html' with slide1_line2='Heading1' %}
  {% else %}
    {% include 'slide_map.html' with slide1_line2='Heading2' %}
  {% endif %}
{% endwith %}

请注意:

  1. 您可以在同一{% with … %} template tag [Django-doc]中定义多个变量;和
  2. {% include … %} template tag [Django-doc]可以有一个{% include … with … %}子句来传递某些额外的参数。