Django中{% with %}标签在{% if %} {% else %}标签内是否可用?

66

所以我想做以下事情:

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

Django告诉我需要另一个 {% endwith %} 标签。有没有什么方法可以重新排列 withs 使其工作,或者句法分析器故意在这方面很随意?

也许我做错了什么。在这种情况下是否有某种最佳实践方法?

2个回答

102

如果您想保持DRY原则,请使用include。

{% 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语句要更加DRY。


7
您可以更加DRY。使用{% include "snipet.html" with a=b %}(尽管这可能是Django的一个最新特性)。 - Patrick
3
get_legally_responsible_party 最为枯燥。 - benzkji
你如何比较字符串? - srccode

16

就像这样:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}
如果HTML太大,而且您不希望重复它,那么最好将逻辑放在视图中。您可以设置此变量并将其传递给模板的上下文:

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

p = (age > 18 && patient) or patient.parent
并且在模板中使用 {{ p }} 即可。

这正是我担心的。我尽力保持DRY原则,但如果这是唯一的办法,那就这样吧。谢谢! - Kelly Nicholes
你如何比较字符串? - srccode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接