【问题标题】:Do Django templates allow for range() in for loops?Django 模板是否允许在 for 循环中使用 range()?
【发布时间】:2018-07-16 04:06:56
【问题描述】:

我尝试在模板中使用 for 循环,但出现错误。

这是神社:

    {% for i in range(1,10) %}
        <h2>{{i}}</h2>
    {% endfor %}

这是错误:

django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '(1,10)' from 'range(1,10)'

我有点困惑。这表明range 有问题,甚至不存在,但我已经看到它在其他 Stack Overflow 帖子中被建议作为解决方案,例如这个: How to simulate while loop in Jinja2

jinja/django 中是否存在范围?如果是,为什么这不起作用,如果不是,最好的选择是什么?

【问题讨论】:

    标签: html django django-templates jinja2


    【解决方案1】:

    我认为没有官方的解决方案。但是有一些解决方法。

    类似的东西可以在模板中使用,“a”将是您想要循环的数字。

    {% for x in "aa" %}
       ...
    {% endfor %}
    

    另一种解决方案是创建一个自定义模板过滤器,您可以给它一个数字并返回:

    range(x)
    

    我能想到的最后一个选项是:

    render_response('template.html', {'range': range(10))
    

    然后做:

    {% for x in range %}
       ...
     {% endfor %}
    

    【讨论】:

      【解决方案2】:

      在 Python 中,可以使用 for 循环对字符串进行迭代。

      例如:

      for ch in '0123456789':
          print(ch)
      

      或者,在 Django 中:

      {% for ch in '0123456789' %}
          <h2>{{ch}}</h2>
      {% endfor %}
      

      【讨论】:

        【解决方案3】:

        首先,django 模板中没有范围标签或函数。

        Answer- 将列表传递给渲染函数。

        这是你的问题:

        {% for i in range(1,10) %}
            <h2>{{i}}</h2>
        {% endfor %}
        

        通过将 range 函数作为生成器传递给 views.py 来替换它

        context={
        'iterator':range(1,10)
        }
        return render(req,'anyname.html',context)
        

        然后在您的模板中,您可以通过以下方式使用:

        {% for i in iterator %}
           <div> {{i}} </div>
        {% endfor %}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-13
          • 1970-01-01
          • 1970-01-01
          • 2012-07-25
          • 2021-10-17
          • 1970-01-01
          相关资源
          最近更新 更多