Search code examples
pythonflaskchartssyncfusionsyncfusion-chart

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


In a chart created in flask application. I have to loop through a dictionary as well as a list. I have this as of now.

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 %}
                            ]                 
                    }],

Top 10 = {"a":10,"b":15,"c":5,"d":8,"e":4,..} and Colors = ["blue", "black", "red"...]

Current output : { x: "a", y: 10, fill = "blue" }, { x: "a", y: 10, fill = "black" }, ....

Expected output for the loop is : { x: "a", y: 10, fill = "blue" }, { x: "b", y: 15, fill = "black" },....


Solution

  • Based on your expected output, you dont really want to have nested for loop of colours within Top10 items. It seems you want a one to one map of Top10 items to colours. If that's the case, @Sefan has given some clue in the answer. Here i can give you the full example in Flask and Jinja way.

    In your view, let's say app.py, you can zip your two data object as below:

    @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))
    

    In your template, let's say breakloop.html:

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

    Results:

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