【发布时间】:2010-06-04 16:58:19
【问题描述】:
我想这样做:
{% for egg in eggs %}
<p>{{ egg.spam }}</p>
{% if egg.is_cool %}
{% myvariable = egg %} // Possible in any way?
{% endif %}
{% endfor %}
请原谅 JavaScript 风格的评论(它显示为对 SO 的评论)
【问题讨论】:
我想这样做:
{% for egg in eggs %}
<p>{{ egg.spam }}</p>
{% if egg.is_cool %}
{% myvariable = egg %} // Possible in any way?
{% endif %}
{% endfor %}
请原谅 JavaScript 风格的评论(它显示为对 SO 的评论)
【问题讨论】:
我认为最接近的是with 标签:http://docs.djangoproject.com/en/dev/ref/templates/builtins/#with。
如果您说尝试在模板中突出显示某个项目,我可以想象这样做:
<div class="special">
{% with some_list.first as special_item %}
{{ specialitem }}
{% endwith %}
</div>
<div class="everything">
{% for item in some_list %}
{{ item }}
{% endfor %}
</div>
如果你想要一些特殊的逻辑来确定哪个是特殊项目,我会向对象添加一个方法(所以你最终得到:{% with some_collection.my_method as special_item %} 以上)或者在将特殊项目传递给视图之前确定它.希望对您有所帮助。
【讨论】:
with 标签本身就是一个循环。我需要稍后在页面中访问myvariable。
欢迎使用 Django 模板。
这个问题很容易通过发布到 DjangoSnippets.com 的最早的 sn-ps 之一解决:Expr tag。
人们可以整天争论逻辑与模板的分离,但这忽略了模型或视图中的 业务逻辑,以及 表示逻辑 仅属于模板中的。如果您有很多表示逻辑,您可能需要考虑为部分或全部模板使用Jinja2。警告:虽然 Jinja2 看起来很像 Django 的模板语言,但与 Custom Template Tags 之类的东西不兼容。
【讨论】:
是的,您可以使用with 构造:
{% with myvariable as egg %}
do stuf
{% endwith %}
【讨论】:
The populated variable (in the example above, total) is only available between the {% with %} and {% endwith %} tags.
我认为最好在视图中执行这种测试和设置行为,而不是在模板中。如果有的话,它可以让您在需要时更好地控制缓存。
【讨论】: