具有多个行的 Django 模板中的交替行着色 [英] Alternate Row Coloring in Django Template with More Than One Set of Rows

查看:18
本文介绍了具有多个行的 Django 模板中的交替行着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 模板提供了内置标签 cycle 用于在模板中不同点的几个值之间交替(或模板中的 for 循环),但是当它在外部范围内访问时,此标签不会重置cycle 的定义.即,如果您的模板中有两个或更多列表,那么您希望使用一些 css 定义 oddeven 的所有行,第一行一个列表会从最后一个停止的地方开始,而不是从选择(oddeven)中进行新的迭代

例如,在下面的代码中,如果第一个博客的条目数为奇数,那么第二个博客中的第一个条目将以 even 开始,当我希望它从 奇数.

{% for blog in blogs %}{% 用于 blog.entries 中的条目 %}<div class="{% cycle 'odd' 'even' %}" id="{{entry.id}}">{{entry.text}}

{% 结束为 %}{% 结束为 %}

我已经尝试通过使用此处提供的 resetcycle 标记进行修补来避免这种情况:

Django 票证:循环标签超出范围后应重置

无济于事.(代码对我不起作用.)

我也试过将我的内循环移到自定义标记中,但这也不起作用,也许是因为编译/渲染循环将循环移回外循环?(不管为什么,它对我不起作用.)

我怎样才能完成这个简单的任务!?在我看来,我不希望使用预编译的信息来创建数据结构;这似乎没有必要.提前致谢.

解决方案

最简单的解决方法(直到修复并应用了 resetcycle 补丁)是使用内置的divisibleby"过滤器和 forloop.counter:

{% for entry in blog.entries %}<div class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}" id="{{ entry.id }}">{{ entry.text }}

{% 结束为 %}

有点冗长,但不难理解,而且效果很好.

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 cycles 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)

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

I've tried obviating this by patching with the resetcycle tag offered here:

Django ticket: Cycle tag should reset after it steps out of scope

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.

解决方案

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屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆