如何在Jinja python的for循环中添加变量

如何在Jinja python的for循环中添加变量,python,django,jinja2,Python,Django,Jinja2,我试图通过添加产品范围,在django中使用for循环遍历产品列表{more so a queryset} 以下代码在cmd提示符下打印时有效 for card in allproduct[nextRangePage:limit]: print(card.name) 但由于某些原因,金贾模式失败了 {% for card in product[{%'nextRangePage'%}:{%'limit'%}] %} 错误是 django.template.exceptions.Temp

我试图通过添加产品范围,在django中使用for循环遍历产品列表{more so a queryset} 以下代码在cmd提示符下打印时有效

for card in allproduct[nextRangePage:limit]:
    print(card.name)
但由于某些原因,金贾模式失败了

{% for card in product[{%'nextRangePage'%}:{%'limit'%}] %}
错误是

django.template.exceptions.TemplateSyntaxError:无法分析其余部分:'allproduct[{%'nextRangePage''中的'[{%'nextRangePage''

上下文变量包括:

context = {
'product': product_list,
'pages': pages,
'nextRangePage': nextRangePage,
}

[product\u list=allproduct]

您永远不会嵌套Jinja
{…}
{%…%}
标记。而不是:

{% for card in product[{%'nextRangePage'%}:{%'limit'%}] %}
你需要:

{% for card in product[nextRangePage:limit] %}
例如,给定以下代码:

import jinja2

product = [{'name': f'item{i}'} for i in range(10)]

t = jinja2.Template('''
{% for card in product[nextRangePage:limit] %}
{{ card }}
{% endfor %}
''')

print(t.render(product=product, nextRangePage=2, limit=8))
输出为:

{'name': 'item2'}

{'name': 'item3'}

{'name': 'item4'}

{'name': 'item5'}

{'name': 'item6'}

{'name': 'item7'}

try:
{%forallproduct | slice:limit%}
{%forallproduct | slice(limit)%}
它不起作用,给了一个错误'forx in y':%s”%token.contents)django.template.exceptions.TemplateSyntaxError:'for'语句应该使用格式'forx in y':forallproduct | slice:limit中的卡