Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS + twig symfony

I've got an issue, I'm trying to create a chart (pie) with ChartJS using twig data.

The chart label uses an array, so I'm giving a twig array to it like this :

var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ({{array|json_encode()|raw}})

But it displays "object Object". For my purpose I want to display an attribute of that object, in that example : "intitule"

My array

Thanks a lot.

like image 780
Cesar Avatar asked Jan 19 '26 10:01

Cesar


1 Answers

I suggest you write an own Twig extension and add a filter function to it:

1. Create the extension class and add a filter with name chart:

// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('chart', array($this, 'chartFilter')),
        );
    }

    public function chartFilter($items, $key = 'intitule')
    {
        $output = [];
        foreach ($items as $item {
            if (array_key_exists($key, $item)) {
                $output[] = $item[$key];
            }   
        }    

        return json_encode($output));
    }
}

2. Create service

Depending on your services.yml definition you may need to create a service for the extension:

app.twig_extension:
    class: AppBundle\Twig\AppExtension
    tags:
        - { name: twig.extension }

3. Use the filter in your view

you can use the filter using it like this:

var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ({{array|chart|raw}})
like image 86
lordrhodos Avatar answered Jan 21 '26 01:01

lordrhodos