循环模板标记仅适用于固定数量的参数

时间:2022-11-27 09:12:53

I'm using the template tag cycle to add different css classes to an element dependent on the index of a loop in a Django template. See following example:

我正在使用模板标记循环向依赖于Django模板中循环索引的元素添加不同的css类。请参阅以下示例:

{% for id in menus %}
    <div class="col-md-2 {% cycle 'col-md-offset-1' %}">
    </div>
{% endfor %}

This throws an No named cycles in template. ''col-md-offset-1'' is not defined Error.

这会在模板中抛出一个没有命名的循环。 ''col-md-offset-1''未定义错误。

The menuslist has 5 entries and if I adjust the number of arguments for the cycle method to the number of list entries it works:

menuslist有5个条目,如果我将循环方法的参数个数调整为它的工作列表条目数:

{% for id in menus %}
    <div class="col-md-2 {% cycle 'col-md-offset-1' '' '' '' ''%}">
    </div>
{% endfor %}

Does the cycle template tag always needs to have the exact number of arguments as the used list? This sounds wrong to me.

循环模板标记是否总是需要具有确切的参数数量作为使用的列表?这对我来说听起来不对。

Is there a different way to set a class only for the first element?

是否有另一种方法只为第一个元素设置类?

1 个解决方案

#1


1  

I don't understand why you're trying to use cycle for only one thing. That doesn't make sense.

我不明白为什么你只想用一个东西来循环。这没有意义。

If you want to set a class for the first element only, use {% if forloop.first %}.

如果要仅为第一个元素设置类,请使用{%if forloop.first%}。

#1


1  

I don't understand why you're trying to use cycle for only one thing. That doesn't make sense.

我不明白为什么你只想用一个东西来循环。这没有意义。

If you want to set a class for the first element only, use {% if forloop.first %}.

如果要仅为第一个元素设置类,请使用{%if forloop.first%}。