简体   繁体   中英

How can I access data provided to HTML template from Python flask routing in my JavaScript code?

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
    });
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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