i have an issue trying to get the twig values in the html and taking the data for a script that shows a pie chart with chart.js in the html
This is how im adding the current project values from the db in the php controller
$TEMPLATE_DATA['PROJECTS'] = $projects;
But the field with the data that i need is a json that look like this {"name":"test","size":"348"}
So what i did in the html was doing a for loop for storing in a twig variable the array for that
{% set brands = [] %}
{% for project in PROJECTS %}
{% if project.name %}
{% set brands = brands|merge([project.name]) %}
{% endif %}
{% endfor %}
{% for brand in brands %}
{{ brand |json_encode}}
{% endfor %}
this only gets the current names for the projects but ive also need other data from that json, the problem comes when i need to set the data variables for the chart, this is the script
<script>
var foo ='{{ brands |json_encode }}';
console.log(foo);
console.log(typeof(foo));
// console.log(foo);
var data = {
labels: [
"Project 1",
"Project 2",
"Remaining"
],
datasets: [
{
// data: [30, 40, 13],
data: foo,
backgroundColor: [
"#FF6384",
"#36A2EB",
// "#FFCE56",
// "#9861B1",
// "#007D6F",
// "#FF5D4D",
// "#3B4856",
"#9FADBD"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
// "#FFCE56",
// "#9861B1",
// "#007D6F",
// "#FF5D4D",
// "#3B4856",
"#9FADBD"
]
}]
};
var ctx = document.getElementById("myChart");
var options = {
responsive: true,
legend: {
position: 'bottom'
},
// tooltips: {
// callbacks: {
// label: function(tooltipItem) {
// return "%" + Number(tooltipItem.yLabel) + " usage";
// }
// }
// },
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: function (tooltipItem, data) {
return " " + data.labels[tooltipItem[0].index];
},
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']] + " Kb";
},
// label: function(tooltipItems, data) {
// return "Total usage: " + tooltipItems.yLabel + ' €';
// },
// footer: function (tooltipItem, data) { return "..."; }
}
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = ctx.dataset._meta[0].total;
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
}
};
var myPieChart = new Chart(ctx,{
type: 'pie',
data: data,
options: options
});
</script>
But at the end i just getting an a String and not a array of the names, and i cant find a way of using that data to use it in the current chart