Chartjs-Passing data from Express to HTML (Pug) to display Chart.js

0👍

{{var1}}, <<%= var1 >> are the syntaxes for Handlebars and EJS respectively.

for Pug it’ll be #{var1}.

An example code snippet below

Read the HTML/template file and replace the identifier with chart data.

The pug file below.

doctype html
html
  head
    title my chart application
    meta(charset='utf-8')
    | **
    script(src='https://cdn.jsdelivr.net/npm/chart.js')
    | **
    style.
      
  body
    canvas#test
    script.
      var data = {
         labels: ["Mon", "Tue", "Wed", "Thu", "Fri"],
         datasets: [
              {
                label: "My data",
                fillColor: "rgba(189,156,221,0.2)",
                strokeColor: "rgba(189,156,221,1)",
                pointColor: "rgba(189,156,221,1)",
                pointStrokeColor: "#111",
                pointHighlightFill: "#000",
                pointHighlightStroke: "rgba(189,156,221,1)",
                data: #{myChartInfo}
              }
            ]
         };
      
      var ctx = document.getElementById("test").getContext("2d");
      var myChart = new Chart(ctx).Line(data);

Nodejs

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    fs.readFile('index.pug', 'utf-8', function (err, data) {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        const chartData = 'some data';
        const result = data.toString('utf8').replace('#{myChartInfo}', JSON.stringify(chartData));
        res.write(result);
        res.end();
    });
}).listen(3000);

The #{myChartInfo} in the HTML/templating engine is replaced with the data at the server-side.

Leave a comment