Home > OS >  Template variable injection in JS script
Template variable injection in JS script

Time:12-31

I have encountered a quite peculiar issue in my flask app trying to inject a template variable withing a Js script , I don't really understand what the problem is so here it goes.

I am specifically trying to inject two variables: a list of numbers and a list of strings (same length), so that I can plot the data on a chart.js plot.

The problem is that when injecting a single variable (the list of numbers) the page renders the pie chart with no errors, but then when i add the second variable (list of strings) the page goes blank.

Here is the JS snippet:

 <div class='chart'>
    <canvas id="myChart" width="400" height="400"></canvas>
    <script type="text/javascript">
    var data = {{values}};
    var labels = {{labels}};
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                labels: '# of Votes',
                data: data,
                backgroundColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255,1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    </script>

And flask:

@app.route('/test')

def test():
    screener = Signals()
    major_news = screener.major_news()
    distribution = screener.industry_distribution(major_news)
    
    return render_template('test.html', labels=[str(key) for key in distribution], values=[distribution[key] for key in distribution])

Keep in mind that the variables have both been checked and they both contain what they should.

In the JS script the labels variable is doing nothing but still throws an error as soon as declared.

Thanks for helping.

CodePudding user response:

Refering to this SO Answer https://stackoverflow.com/a/48237270/17798307

Flask provides a Jinja filter for this: tojson dumps the structure to a JSON string and marks it safe so that Jinja does not autoescape it.

Please try to declare your variables like this:

var labels = {{labels | tojson}};
  • Related