简体   繁体   English

使用 Jinja2 和 for 循环

[英]Using Jinja2 and for loop

I am very new to Jinja2 and I want to show 3 different things in line, repeating it 2 times so I get 3x3 block.我对 Jinja2 很陌生,我想在线显示 3 个不同的东西,重复 2 次所以我得到 3x3 块。 Here is my code now:这是我现在的代码:

{% for item in recommendations('someID', 3) %}

This gives me only 3 things which are displayed vertically.这给了我只有 3 个垂直显示的东西。 How can I make it to display 3 things horizontally and then repeat it 2 more times?我怎样才能让它水平显示 3 个东西,然后再重复 2 次? Thank you in advance.先感谢您。

If we take a function from this question's answer, and prepare our array by splitting it into a desired length chunks, so that we have array of a format [['a'. 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]如果我们从这个问题的答案中获取一个函数,并通过将其拆分为所需长度的块来准备我们的数组,这样我们就有了格式为[['a'. 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] [['a'. 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] , we will be able to use a simple nested for loop in Jinja to accomplish this task. [['a'. 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] ,我们将能够使用一个简单的嵌套 for 循环Jinja 来完成这个任务。

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

{% for subArray in array %}
       {% for element in subArray %}
           {{ element }}, 
       {% endfor %}
       <br />
{% endfor %}

This should result in:这应该导致:

a,b,c,
d,e,f,
g,h,i,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM