In Javascript, how do I access data from an array, using PUG / Jade view?

0

I'm using Express on Nodejs and also use PUG (or old Jade) in views. In a view I display the data taken from a database in a chart. The data I already receive in array format. I created a small Javascript script to generate the graph.

DOUBT : How do I get this array data to be accessed from within this Javascript as indicated in my code below? How do I pass the data to Javascript?

view.pug

doctype html
html
  head
    title= title
    meta("charset=utf-8")
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src="./javascripts/chartjs/Chart.js")
  body
    block content
        form.form-horizontal.well(method="post", action="/report")
            script
                include ../public/javascripts/chart-gen.js

chart-gen.js: file that made an include just above:

    var dataValues = valoresDoBancoDeDados;  <<<==== dados vindos do banco de dados (array)
    var dataLabels = labelsDoBancoDeDados;   <<<==== dados vindos do banco de dados (array)

    var data = {
        labels: dataLabels, 
        datasets: [
            {
                label: "Quantidade de veículos",
                backgroundColor: 'rgb(132,199,200)', 
                data: dataValues 
            }    
        ]
    };

    var chrt = document.getElementById("canvas_chart").getContext("2d");
    var mChart = new Chart(chrt, {
       type: 'line',
       data: data
    });

HTML: It should soon be this way :

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <script src="./javascripts/chartjs/Chart.js"></script>
</head>
<body>
    <form class="form-horizontal well" method="post" action="/report">

      <div style="position: relative; height:320px; width:600px;">
        <canvas id="canvas_chart"></canvas>
      </div>

      <script>    
            var dataValues = valoresDoBancoDeDados;  <<<==== dados vindos do banco de dados (array)
            var dataLabels = labelsDoBancoDeDados;   <<<==== dados vindos do banco de dados (array)

            var data = {
                labels: dataLabels, 
                datasets: [
                    {
                        label: "Quantidade de veículos",
                        backgroundColor: 'rgb(132,199,200)', 
                        data: dataValues
                    }    
                ]
            };

            var chrt = document.getElementById("canvas_chart").getContext("2d");
            var mChart = new Chart(chrt, {
               type: 'line',
               data: data
            });
      </script>

    </form>
</body>
</html>
    
asked by anonymous 30.07.2017 / 02:23

1 answer

0

Correct form:

view.pug

    script(type='text/javascript')
        | var dataValues = valoresDoBancoDeDados;
        | var dataLabels = labelsDoBancoDeDados;
        include ../public/javascripts/chart-gen.js
    
30.07.2017 / 18:31