1

So I have a python flask application that routes to a site and passes along two lists:

def chart():
    labels = ['x', 'y', 'z']
    values = [100, 150, 100]
    return render_template('chart.html',
     labels=labels, values=values)

I use Chart.min.js and I can then use the lists in rendering a graph in my chart.html:

{% block body %}
<h1>Test chart</h1>

<canvas id="myChart" width="800" height="400"></canvas>

<p id="caption">chart displaying labels n' values</p>

<script type=text/javascript>

    var ctx = document.getElementById('myChart');

    var names = [
        {% for item in labels %}
            "{{ item }}",
        {% endfor %}
    ];

    var numbers = [
        {% for item in values %}
            {{ item }},
        {% endfor %}
    ];

    var chartData = {
        labels: names,
        datasets: [{
          label: 'values',
           data: numbers
        }]
    };

    var myChart = new Chart(ctx, {
        type: 'line',
        data: chartData
    });

</script>

{% endblock %}

Now this works fine and I get a nice pretty graph. Then I wanted to put my JavaScript in a seperate file in the static folder for my flask application but I cannot find how I'm supposed to access the lists passed along to chart.htlm. I can render a graph just fine if I hardcode some data into the JS file but I can't seem to get the data provided by the python code..

var ctx = document.getElementById('myChart');

// var names = ['x', 'y', 'z'];
// var numbers = [100, 150, 100];

var chartData = {
    labels: names,
    datasets: [{
        label: 'values',
        data: numbers
    }]
};

var myChart = new Chart(ctx, {
    type: 'line',
    data: chartData
});

I have tried to loop the contents of the lists from my python file into different containers such as <div>, <ol> and <ul>and access those through document.getElementById("") among some other attempts, can't really remember them all.

I have tried to find the answer on google but to no avail.

Any help is appreciated and I should mention that I'm new to these coding languages and frameworks so please have some oversight if what I am missing is obvious.

=== NEW WORKING VERSION ===

chart.html :

<script type="text/javascript">

    window.addEventListener('DOMContentLoaded', (event) => {
        const myChart2 = document.getElementById('ChartOne');
        drawChart(ChartOne, {{ labels| tojson }}, {{ values| tojson }}, ChartType.LINE);

    });

</script>

<div>
    <canvas id="ChartOne" width="800" height="400"></canvas>
    <p id="caption">line chart displaying labels n' values</p>
</div>

script.js:

const ChartType = {
    LINE: "line" // add more variables for more chart options
}

function drawEmployeeChart(ctx, labels, values, chartType) {
    var chartData = {
        labels: labels,
        datasets: [{
            label: 'values',
            data: values,
        }]
    };

    var myChart = new Chart(ctx, {
        type: chartType,
        data: chartData
    });
}

1 Answer 1

1

Now that you've separated your javascript into a new js file, you have to get your variables there.

What you could do is define a javascript function in your .js file that takes two arrays:

function render_chart(labels, values)
{
    var ctx = document.getElementById('myChart');

    var chartData = {
        labels: names,
        datasets: [{
            label: 'values',
            data: values
        }]
    };

    var myChart = new Chart(ctx, {
        type: 'line',
        data: chartData
    });
}

Then call the function from your chart.html page, but you have to convert the variables you pass from Flask to json. To do that do this, using the special tojson Jinja2 filters:

<script type="text/javascript">render_chart({{ labels|tojson }}, {{ values|tojson }})'></script>
Sign up to request clarification or add additional context in comments.

4 Comments

Hey! Thanks to alot! Right, I understood what you meant :) This works but I have a follow-up question: I get syntax errors when I implement <body onload='render_chart({{ labels|tojson }}, {{ values|tojson }})'> that tell me Property assignments and Argument expressions are expected. What could be the cause of this? Further, my chart.html is extended from my index.html by {{ extends 'index.html }} blocks and my index.html already have a body tag. Is it possible to use another tag where I can call my JS function?
@shurda Do you have a script block at the bottom of the html page? In there you could put this: <script type="text/javascript">render_chart({{ labels|tojson }}, {{ values|tojson }});</script>
Yes I have a script block, tried your solution and it worked fine. Modified it further to be more generic. Posting the extended version for people to see. Thanks again!
Thanks! And thank you for the help, I really appreciate it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.