{%if%} {%else%}标记内的Django {%with%}标记?

Kel*_*les 39 django templates if-statement with-statement

所以我想做以下事情:

{% if age > 18 %}
    {% with patient as p %}
{% else %}
    {% with patient.parent as p %}
    ...
{% endwith %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

但Django告诉我,我需要另一个{%endwith%}标签.是否有任何方法可以重新排列withs以使其工作,或者语法分析器是否有目的无忧无虑的这种事情?

也许我会以错误的方式解决这个问题.在涉及到这样的事情时,是否有某种最佳实践?

Ted*_*Ted 64

如果你想保持干爽,请使用包含.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}
Run Code Online (Sandbox Code Playgroud)

或者,更好的是在封装核心逻辑的模型上编写一个方法:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent
Run Code Online (Sandbox Code Playgroud)

然后在模板中:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 
Run Code Online (Sandbox Code Playgroud)

然后在将来,如果谁负责合法的逻辑变化,你就有一个地方可以改变逻辑 - 比在十几个模板中更改if语句要多得多.

  • 你可能是DRYer.使用`{%include'snipet.html"with a = b%}`(虽然这可能是最近的Django事情) (4认同)
  • `get_legally_responsible_party`是最干的. (2认同)

Gab*_*oss 9

像这样:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

如果html太大而你不想重复它,那么逻辑最好放在视图中.您设置此变量并将其传递给模板的上下文:

p = (age > 18 && patient) or patient.parent
Run Code Online (Sandbox Code Playgroud)

然后在模板中使用{{p}}.