如何在 Jinja 模板上添加索引?

huangapple go评论96阅读模式
英文:

How add index on a jinja template?

问题

我通过我的Python代码将列表传递给我的Jinja模板。

```python
list = [123,232,334,412]

如何在输出中添加索引?

例如:

一些文本 id1 = 123,id2 = 232,id3 = 334,id5 = 412

我尝试过:

一些文本 {{ list | join(',id') }}

但输出中没有索引:

一些文本 id = 123,id = 232,id = 334,id = 412

<details>
<summary>英文:</summary>

I&#39;m passing list to my Jinja template through my Python code.

```python
list = [123,232,334,412]

How can I add an indexing to the output ?

For example:

some text id1 = 123, id2 = 232, id3 = 334, id5 = 412

What I tried was:

some text {{ list | join(&#39;, id = &#39; ) }}

But the output contains no indexes:

some text id = 123, id = 232, id = 334, id = 412

答案1

得分: 1

你可以使用loop.index来获取这个值。

英文:

you may use loop.index to get this.

from jinja2 import Template
s = &quot;{% for element in elements %}id{{loop.index}} element {% endfor %}&quot;

template = Template(s)
idx = template.render(elements=[123,232,334,412])

print(idx)

output

id1 element id2 element id3 element id4 element 

huangapple
  • 本文由 发表于 2023年7月17日 15:29:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定