【问题标题】:Django {% with %} tags within {% if %} {% else %} tags?{% if %} {% else %} 标签内的 Django {% with %} 标签?
【发布时间】:2011-10-28 03:10:08
【问题描述】:

所以我想做如下的事情:

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

但是 Django 告诉我我需要另一个 {% endwith %} 标签。有没有什么办法可以重新安排这些东西来完成这项工作,或者语法分析器是否故意对这类事情不关心?

也许我用错了方法。当涉及到这样的事情时,是否有某种最佳实践?

【问题讨论】:

    标签: django templates with-statement if-statement


    【解决方案1】:

    如果您想保持 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 语句要干得多。

    【讨论】:

    • 你可能是 DRYer。使用{% include "snipet.html" with a=b %}(虽然这可能是最近 Django 的事情)
    • get_legally_responsible_party 最干燥。
    • 如何与字符串比较?
    【解决方案2】:

    像这样:

    {% 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 }}。

    【讨论】:

    • 这就是我所担心的。我尽量保持干燥,但如果这是唯一的方法,那就这样吧。谢谢!
    • 如何与字符串比较?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2014-07-25
    • 2014-04-03
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多