[Fixed] EJS Tags with ChartJS?

Issue

Is it possible to use EJS tags to add data to a graph? Here is my current graph’s data:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    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: [10, 20, 81, 56, 55, 40],
        }
    ]
};

I’m wanting to do something like this:

labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]

How would I accomplish using EJS tags to populate the graphs data? (NOTE: The EJS tag info would have already been saved the user before the chart needs to be generated)

Solution

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); %>,
    }
  ]
};

Leave a Reply

(*) Required, Your email will not be published