Django {% with %} 标签位于 {% if %} {% else %} 标签内?
所以我想做如下的事情:
{% if age > 18 %}
{% with patient as p %}
{% else %}
{% with patient.parent as p %}
...
{% endwith %}
{% endif %}
但是 Django 告诉我我需要另一个 {% endwith %} 标签。有没有办法重新排列 withs 来完成这项工作,或者语法分析器是否故意对这类事情不关心?
也许我的处理方式是错误的。对于这样的事情,是否有某种最佳实践?
So I want to do something like follows:
{% if age > 18 %}
{% with patient as p %}
{% else %}
{% with patient.parent as p %}
...
{% endwith %}
{% endif %}
But Django is telling me that I need another {% endwith %} tag. Is there any way to rearrange the withs to make this work, or is the syntactic analyzer purposefully carefree in regards to this sort of thing?
Maybe I'm going about this the wrong way. Is there some sort of best practice when it comes to something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想保持 DRY,请使用 include。
或者,更好的方法是在模型上编写一个封装核心逻辑的方法:
然后在模板中:
然后在将来,如果法律责任人的逻辑发生变化,您可以在一个地方更改逻辑 - 远比必须更改十几个模板中的 if 语句更干燥。
if you want to stay DRY, use an include.
or, even better would be to write a method on the model that encapsulates the core logic:
Then in the template:
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.
像这样:
如果html太大并且你不想重复它,那么逻辑最好放在视图中。您设置此变量并将其传递到模板的上下文:
然后在模板中使用 {{ p }} 。
Like this:
If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:
and then just use {{ p }} in the template.