62

所以我想做如下的事情:

{% if age > 18 %}
    {% with patient as p %}
{% else %}
    {% with patient.parent as p %}
    ...
{% endwith %}
{% endif %}

但是 Django 告诉我我需要另一个 {% endwith %} 标签。有没有什么办法可以重新安排这些东西来完成这项工作,或者句法分析器对这类事情有目的地无忧无虑?

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

4

2 回答 2

95

如果您想保持 DRY,请使用包含。

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

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

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

然后在模板中:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

然后在未来,如果谁应负法律责任的逻辑发生变化,您可以在一个地方更改逻辑——比必须更改十几个模板中的 if 语句要干得多。

于 2011-08-16T16:54:55.613 回答
13

像这样:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}

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

p = (age > 18 && patient) or patient.parent

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

于 2011-08-16T14:30:48.283 回答