在 jinja 中进行 1 次迭代后如何在循环后中断?

How can I break after the loop after 1 iteration in jinja?

在 Flask 应用程序中创建的图表中。我必须遍历字典和列表。我现在有这个。

series:
                    [{
                            points: [
                            
                            {% for key, value in Top10.items() %}
                                {% for color in colors%}
                                       { x: "{{key}}", y: {{ value }}, fill = "{{ color }}" }, //"" as it is a string
                                    {% endfor %}
                                {% endfor %}
                            ]                 
                    }],

前 10 名 = {"a":10,"b":15,"c":5,"d":8,"e":4,..} 和 颜色 = [“蓝色”、“黑色”、“红色”...]

当前输出:{ x: "a", y: 10, fill = "blue" }, { x: "a", y: 10, fill = "black" }, ....

循环的预期输出是:{ x: "a", y: 10, fill = "blue" }, { x: "b", y: 15, fill = "black" },....

您可以使用 zip 和 iteritems() 来压缩字典和列表。并循环遍历压缩列表。

Top10 = {"a":10,"b":15,"c":5,"d":8,"e":4}
Colors = ["blue", "black", "red"]
Zipped = zip(Top10.iteritems(), Colors)

for (key, value), color in Zipped:
    print(key,value,color)

根据您的预期输出,您真的不想在 Top10 项目中嵌套颜色循环。您似乎想要一张 Top10 项目与颜色的一对一映射。如果是这样的话,@Sefan 在答案中给出了一些线索。在这里我可以用 Flask 和 Jinja 的方式给你完整的例子。

在您看来,假设 app.py,您可以将两个数据对象压缩如下:

@app.route('/breakloop')
def breakloop():
    Top10 =  {"a":10,"b":15,"c":5,"d":8,"e":4}
    colors = ["blue", "black", "red"]

    return render_template('breakloop.html', zipped=zip(Top10.items(), colors))

在您的模板中,假设 breakloop.html:

{% for (key, value), color in zipped %}
        { x: "{{key}}", y: {{ value }}, fill = "{{ color }}" }, </br> 
{% endfor %}

结果:

{ x: "a", y: 10, fill = "blue" }, 
{ x: "b", y: 15, fill = "black" }, 
{ x: "c", y: 5, fill = "red" }, 

我们已经根据您的要求准备了样品。为此,我们根据您的要求创建了数据。

  public top10: Object = { a: 10, b: 15, c: 5, d: 8, e: 4 };
  public colors: string[] = ['blue', 'black', 'red', 'yellow', 'green'];
  public data: Object[] = this.getData();
  public getData(): Object[] {
    let count = 0;
    let currentData: Object[] = [];
    for (const [key, value] of Object.entries(this.top10)) {
      currentData.push({
        x: `${key}`,
        y: `${value}`,
        fill: this.colors[count++]
      });
    }
    count = 0;
    return currentData;
  }
<ejs-chart>
    <e-series-collection>
       <e-series [dataSource]='data' xName='x' yName='y' pointColorMapping="fill">
       </e-series>
     </e-series-collection>
</ejs-chart>

示例 link:https://stackblitz.com/edit/angular-tjjts9?file=app.component.html