[英]How to add variables inside the for loop of Jinja python
I am trying to loop over a product list{more so a queryset} in django using for loop, by adding the range of products The following code works when printed out in cmd prompt我正在尝试使用 for 循环在 django 中循环遍历产品列表{more so a queryset},通过添加产品范围以下代码在 cmd 提示符下打印时有效
for card in allproduct[nextRangePage:limit]:
print(card.name)
But the Jinja pattern fails for some reason但是 Jinja 模式由于某种原因失败了
{% for card in product[{%'nextRangePage'%}:{%'limit'%}] %}
The error is错误是
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[{%'nextRangePage'' from 'allproduct[{%'nextRangePage'' django.template.exceptions.TemplateSyntaxError:无法解析余数:'[{%'nextRangePage'' from 'allproduct[{%'nextRangePage''
The context variables are:上下文变量是:
context = {
'product': product_list,
'pages': pages,
'nextRangePage': nextRangePage,
}
[product_list = allproduct] [product_list = allproduct]
You never nest Jinja {{...}}
or {%...%}
markers.你永远不会嵌套 Jinja
{{...}}
或{%...%}
标记。 Instead of:代替:
{% for card in product[{%'nextRangePage'%}:{%'limit'%}] %}
You need:你需要:
{% for card in product[nextRangePage:limit] %}
For example, given the following code:例如,给定以下代码:
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))
The output is:输出是:
{'name': 'item2'}
{'name': 'item3'}
{'name': 'item4'}
{'name': 'item5'}
{'name': 'item6'}
{'name': 'item7'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.