Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
Template variable injection in JS script

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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}};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda