[Chartjs]-EJS Tags with ChartJS?

9👍

Yes, you can use EJS tags or any other similar tag used across the various view javascript frameworks (e.g. handlebars, spacebars in meteor, ejs, etc.). Chart.js is initialized at runtime, so it has no knowledge of how the data made its way into the file (e.g. it doesn’t know…nor does it care…that your javascript was pre-processed and generated).

The format of the tag itself just has to do with the variables in which you stored your data. I would recommend storing your labels and data in arrays and using JSON.stringify().

// defined in your app
var labels = ['label 1', 'label 2', ...];
var data = [datapoint1, datapoint2, ...];

// in your EJS file.
var canvas = document.getElementById('myChart');
var data = {
  labels: <%- JSON.stringify(labels); %>,
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: <%- JSON.stringify(data); %>,
    }
  ]
};

0👍

The easiest way is to use JSON.stringify() in EJS tags. You can do

labels: <%- JSON.stringify(data.labels); %>,
data: <%- JSON.stringify(data.datasets.data); %>

It’s based on your data variable. So, you may need to adjust this code accordingly.

0👍

An example, modifying the Google Chart Quickstart Example would help out a great deal. I attempted the below with no luck.

Two files:
chart.js to create the data and chart.ejs template to be renderedL:

Here’s what I put together so far:
chart.js

import { dirname } from "path";
import express from "express"
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
let myData = [
  ['Mushrooms', 3],
  ['Onions', 1],
  ['Olives', 1],
  ['Zucchini', 1],
  ['Pepperoni', 2],
  ['Pineapple',12],
  ['Green Peppers',22]
  ]
  
  let myGraph ={}
  myGraph.name="First Chart"
  myGraph.myData=myData

  const app = express();

  app.get('/', (req, res) => {
    const templatePath = __dirname+"/views/chart.ejs";
    res.render(templatePath,{ graphs: myGraph })
    
});

  app.listen(3000, () => {
    //openBrowser('http://localhost:3000');
    console.log("Server running on localhost:3000")
  });

and chart.ejs

This is what I have so far:

<!DOCTYPE html>
<html lang="en">

</html>
<html>

<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', { 'packages': ['corechart'] });
        google.charts.setOnLoadCallback(drawGraphs);


        function drawGraphs() {
            appendDivToBody(graphs.name, 'width: 1200px; height: 500px');
        const graphs = <%= JSON.stringify(graphs) %>;
            graphs.forEach(g => {
              appendDivToBody(g.name, 'width: 1200px; height: 500px');
              drawGraph(g.name, g.myData);
            });
        }

        function drawGraph(graphName, graphData) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Toppings');
            data.addColumn('number', 'Slices');
            data.addRows(graphData);
            var options = {
                title: `${graphName}`,
                'width': 500,
                'height': 300
            };
            var chart = new google.visualization.PieChart(document.getElementById(graphName));
            chart.draw(data, options);
        }

        function appendDivToBody(id, style) {
            var div = document.createElement('div');
            div.id = id;
            div.style = style;
            document.getElementsByTagName('body')[0].appendChild(div);
        }

    </script>
</head>

<body>
    <% console.log(graphs.name) %>
    <% console.log(graphs.myData) %>

    <p>
        <!-- HTML content goes here -->
        Hello
    </p>
    <ul>
        <%graphs.myData.forEach((item)=> { %>
            <li>
                I had <%=item[1] %> slices of <%=item[0]%> pizza </br>
            </li>
            <%})%>
    </ul>

</body>
</body>

</html>

Leave a comment