PHP Code to prepare the chart data
$context = array();
$context['chart']['labels'] = json_encode(['All', "Active", "Suspended"]);
$context['chart']['dataset'] =json_encode( array_values( 4,3,2 ));
// assuming file is under local/myplugin/templates/chart.mustache
echo $OUTPUT->render_from_template('/local/myplugin/chart', $context) ;
JS Code under template file
/local/myplugin/templates/chart.mustache
<div>
<canvas id="stats" class="aw_chart">
</canvas>
</div>
{{#js}}
require([
'jquery',
'core/chartjs'
], function($, Chart) {
var chart_div = $("#stats"); // @TODO
var chartdata = {
labels:{{{chart.labels}}}, // @TODO
datasets: [{
data: {{{chart.dataset}}}, //@TODO
backgroundColor: ["#fe6384", "#36a2eb", "#fdce56"],
borderWidth: 2
}]
}
var config = {
type: 'doughnut', // pie , bar,
data: chartdata,
options: {
responsive: true,
maintainAspectRatio: false,
aspectRatio: 1,
legend: {
position: 'left',
labels:{
// showing value with legends along with label
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var valueAtIndexOrDefault = Chart.helpers.valueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
return {
text: label + " : " + value,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
}else{
return [];
}
},
usePointStyle: true,
}
},
}
};
chart = new Chart(chart_div, config);
});
{{/js}}