簡體   English   中英

如何在Jinja python的for循環中添加變量

[英]How to add variables inside the for loop of Jinja python

我正在嘗試使用 for 循環在 django 中循環遍歷產品列表{more so a queryset},通過添加產品范圍以下代碼在 cmd 提示符下打印時有效

for card in allproduct[nextRangePage:limit]:
    print(card.name)

但是 Jinja 模式由於某種原因失敗了

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

錯誤是

django.template.exceptions.TemplateSyntaxError:無法解析余數:'[{%'nextRangePage'' from 'allproduct[{%'nextRangePage''

上下文變量是:

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

[product_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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM