Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

python - How do you index on a jinja template?

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]

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}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 example:

{% 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...