【问题标题】:Modulus % in Django templateDjango模板中的模数%
【发布时间】:2012-01-19 14:54:34
【问题描述】:

我正在寻找一种在 django 中使用模数运算符之类的方法。我想要做的是在循环中的每四个元素中添加一个类名。

使用模数看起来像这样:

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

当然这不起作用,因为 % 是保留字符。有没有其他方法可以做到这一点?

【问题讨论】:

  • 你试过了吗? Django 提供了templatetag 标签,但它涵盖了{%%} 等(不是%)。
  • 是的,我试过了,但我收到以下错误:无法解析余数:'%' from '%' 我认为这是因为它不知道如何削减模数。该运算符也未在文档docs.djangoproject.com/en/dev/ref/templates/builtins/… 中列出

标签: python django templates


【解决方案1】:

你需要divisibleby,一个内置的django过滤器。

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

【讨论】:

  • 啊是的,就是这样。现在使用循环,但有利于将来参考。我不想将循环与模 100 或其他东西一起使用 :) 实际上我要把这个答案标记为正确的答案。因为它专注于模数而不是解决方法......
【解决方案2】:

您不能在 Django 模板标签中使用模数运算符,但编写一个过滤器来这样做很容易。像这样的东西应该可以工作:

@register.filter
def modulo(num, val):
    return num % val

然后:

{% ifequal forloop.counter0|modulo:4 0 %}

你甚至可以这样做:

@register.filter
def modulo(num, val):
    return num % val == 0

然后:

{% if forloop.counter0|modulo:4 %}

或者你可以使用cycle标签:

<div class="post width1 height2 column {% cycle 'first' '' '' '' %}">

【讨论】:

    【解决方案3】:

    引导行和列示例。 每 4 项新行。即使少于 4 个项目也要关闭最后一行。

    myapp/templatetags/my_tags.py

    from django import template
    
    register = template.Library()
    
    @register.filter
    def modulo(num, val):
        return num % val
    

    html 模板

    {% load my_tags %}
    
    {% for item in all_items %} 
        {% if forloop.counter|modulo:4 == 1 %}
            <div class="row">
        {% endif %}
    
            <div class="col-sm-3">
                {{ item }}
            </div>
    
        {% if forloop.last or forloop.counter|modulo:4 == 0 %}
            </div>
        {% endif %}
    
    {% endfor %}
    

    【讨论】:

    • 这是更好的答案,因为它描述了需要创建的目录,并且还描述了在模板 html 中加载自定义模板的需要。谢谢。
    【解决方案4】:

    听起来你应该只使用循环标签。 Built-in template tags

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2010-12-19
      • 2010-11-02
      • 2011-05-10
      • 2018-10-02
      • 2013-08-16
      • 2012-01-27
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多