[Chartjs]-ChartJS + twig symfony

3๐Ÿ‘

โœ…

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}})

Leave a comment