您如何在Jinja模板上建立索引? [英] How do you index on a jinja template?

查看:50
本文介绍了您如何在Jinja模板上建立索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过python文件将3个列表传递给我的jinja模板.

I'm passing 3 lists to my jinja template through my python file.

list1 = [1,2,3,4]
list2 = ['a','b','c','d']
list3 = [5,6,7,8]

所有这些值彼此对应,因此1匹配"a"和5,2匹配"b"和6,等等.

All these values correspond with eachother, so 1 matches with 'a' and 5, 2 with 'b' and 6, etc.

在我的模板中,我将它们打印在同一行上. 如何进行数字索引打印出来? 如此

In my template I'm printing them out on the same line. How do I do numerical indexing to print them out? As so

1 a 5
2 b 6
3 c 7

我所知道的唯一一件事就是像这样通过循环直接访问对象

The only thing I know is directly accessing the object through the loop like

 {%for item in list%}
    {{item}}

推荐答案

如果您确实想要索引,则可以对其中一个变量进行循环,然后使用Jinja的loop.index0功能(返回循环开始时的当前索引)从0开始(loop.index从1开始执行相同的操作)

If you really want the index, you could just loop on one of the variables and then uses Jinja's loop.index0 feature (returns the current index of the loop starting at 0 (loop.index does the same thing, starting at 1)

例如:

{% for item in list1 %}

    {{ item }}
    {{ list2[loop.index0] }}
    {{ list3[loop.index0] }}

{% endfor %}

这假设您的列表在设置模板之前都被声明为相同长度,否则您将遇到问题.

This assumes your lists are all asserted to be the same length before setting the template, or you'll encounter problems.

这篇关于您如何在Jinja模板上建立索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆