Search code examples
javascriptpythonjinja2canvasjs

Graphs not showing with Jinja, Flask, and CanvasJS


I am trying to get data from an API, pass it to the template with Jinja, and chart the data using CanvasJS.

When using baked in values, like in the CanvasJS examples, the graph displays properly; however, the second I try to use Jinja to input the values, the chart fails to show.

One reasons for the extra code, is that the API returns date in a "YYYY-MM-DD" form, whereas JS requires the individual values, so I split them using Jinja. Perhaps, I could split them using JS instead.

My CanvasJS code + Jinja looks like this:

window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title:{
            text: "{{ ticker_symbol }}"
        },
        zoomEnabled: true,
        axisY: {
            includeZero:false,
            title: "Prices",
            prefix: "$ "
        },
        axisX: {
            interval:2,
            intervalType: "month",
            valueFormatString: "MMM-YY",
            labelAngle: -45
        },
        data: [
        {
            type: "candlestick",
            dataPoints: [
            {% for key, value in data.items() %}
                {% set dates = key.split("-") %}
                {x: new Date({{ dates[0] }}, {{ dates[1] }}, {{ dates[2] }}]),y:[{{ value['1. open'] }}, {{ value['2. high'] }}, {{ value['3. low'] }}, {{ value['4. close'] }}]},
            {% endfor %}
            ]
        }
        ]
    });
    chart.render();
}

The data is making it to the page, is displayed in the JS when viewing the source of the file in situ.

window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title:{
            text: "MSFT"
        },
        zoomEnabled: true,
        axisY: {
            includeZero:false,
            title: "Prices",
            prefix: "$ "
        },
        axisX: {
            interval:2,
            intervalType: "month",
            valueFormatString: "MMM-YY",
            labelAngle: -45
        },
        data: [
        {
            type: "candlestick",
            dataPoints: [


                {x: new Date(2019, 11, 15]),y:[148.9300, 149.9900, 148.2700, 149.9700]},
                ...(repeated)...
        ]
        }
        ]
    });
    chart.render();
}

But the graph still does not show!

I'm sure there is an issue with how the data is parsed into JS, but I am unable to spot it. One thing I noticed, is that the last date value is accompanied by an annoying "]" that does not seem to want to go away.

Any help would be greatly appreciated, thank you!


Solution

  • There was one major issue:

    I had an extra ] when setting the x: variable for the chart. This is the primary thing that broke the entire graph.

    The Jinja was fine. The JS was fine. My inability to hit {{ }} without making a square bracket was the issue.

    Please commence public flogging.