更新时间:2023-12-04 13:40:16
如果要保持DRY,请使用包含.
if you want to stay DRY, use an include.
{% if foo %}
{% with a as b %}
{% include "snipet.html" %}
{% endwith %}
{% else %}
{% with bar as b %}
{% include "snipet.html" %}
{% endwith %}
{% endif %}
或者,甚至更好的方法是在模型上编写一个封装核心逻辑的方法:
or, even better would be to write a method on the model that encapsulates the core logic:
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语句要干得多.
Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.