Django模板中有多行的替代行着色 [英] Alternate Row Coloring in Django Template with More Than One Set of Rows
问题描述
Django模板提供内置的标签循环
,用于在模板中的不同点(或模板中的循环)中的多个值之间交替,但此标记不会重置在循环
定义之外的范围内访问。也就是说,如果您的模板中有两个或多个列表,那么您希望使用一些css定义 odd
和
,列表的第一行将会选择最后一个关闭的位置,而不是从选项( odd
和 even
)
Django templates offer the builtin tag cycle
for alternating between several values at different points in a template (or for loop in a template) but this tag does not reset when it is accessed in a scope outside of the cycle
s definition. I.e., if you have two or more lists in your template, the rows of all of which you'd like to use some css definitions odd
and even
, the first row of a list will pick up where the last left off, not with a fresh iteration from the choices (odd
and even
)
例如,在下面的代码中,如果第一个博客有奇数个条目,那么第一个条目 c code code code code code code code code code code code $ c
$ b
E.g., in the following code, if the first blog has an odd number of entries, then the first entry in a second blog will start as even
, when I want it to start at odd
.
{% for blog in blogs %}
{% for entry in blog.entries %}
<div class="{% cycle 'odd' 'even' %}" id="{{entry.id}}">
{{entry.text}}
</div>
{% endfor %}
{% endfor %}
尝试通过在这里提供的 resetcycle
标签进行修补来避免这种情况:
I've tried obviating this by patching with the resetcycle
tag offered here:
Django ticket:循环标签应该在超出范围后重新设置
无效。 (这段代码对我来说没有效果。)
to no avail. (The code didn't work for me.)
我也尝试将内部循环移动到自定义标签中,但这也没有起作用,也许是因为编译/渲染循环将循环移回外循环? (不管为什么,它对我来说不起作用。)
I've also tried moving my inner loop into a custom tag, but this also did not work, perhaps because the compile/render cycle moves the loop back into the outer loop? (Regardless of why, it didn't work for me.)
如何完成这个简单的任务!我不希望在我的视图中创建一个数据结构,该信息预编译;这似乎是不必要的。感谢提前。
How can I accomplish this simple task!? I'd prefer not to create a data structure in my view with this information pre-compiled; that seems unnecessary. Thanks in advance.
推荐答案
最简单的解决方法(直到resetcycle修补程序得到修复和应用)是使用内置divisiblebyfilter with forloop.counter:
The easiest workaround (until the resetcycle patch gets fixed up and applied) is to use the built-in "divisibleby" filter with forloop.counter:
{% for entry in blog.entries %}
<div class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}" id="{{ entry.id }}">
{{ entry.text }}
</div>
{% endfor %}
一点点冗长但不难理解非常棒。
A little more verbose, but not hard to understand and it works great.
这篇关于Django模板中有多行的替代行着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!