0

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

3
  • Might help to not quote it if it's not supposed to be a string Commented Jul 8, 2021 at 20:07
  • why not build the json object in your php? Commented Jul 8, 2021 at 21:17
  • 1
    Does this answer your question? Use Javascript to access a variable passed through Twig Commented Jul 9, 2021 at 7:07

1 Answer 1

0

Easiest solution to your problem would be to use | json_encode pipe in twig, and parse it into JSON with JSON.parse to a javascript variable. Here's a brief example:

const dataAsJson = JSON.parse({{ brands |json_encode }});

Add backticks if needed.

Sign up to request clarification or add additional context in comments.

1 Comment

This is incorrect as json_encode does not mark output as safe. Also JSON.parse is not required - demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.