【问题标题】:How to add variables inside the for loop of Jinja python如何在 Jinja python 的 for 循环中添加变量
【发布时间】:2020-05-11 10:49:22
【问题描述】:

我正在尝试使用 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]

【问题讨论】:

  • 试试:{% for card in allproduct | slice:limit %}{% for card in allproduct | slice(limit) %}
  • 它没有用,给出一个错误 'for x in y': %s" % token.contents) django.template.exceptions.TemplateSyntaxError: 'for' 语句应该使用format 'for x in y': for card in allproduct | slice:limit

标签: python django jinja2


【解决方案1】:

您永远不会嵌套 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'}

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 2018-05-21
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2012-03-15
    相关资源
    最近更新 更多