2017-06-15 75 views
1

我有一个问题,我试图创建ChartJS使用树枝数据的图表(饼)。ChartJS + twig symfony

图表标签使用数组,所以我给一个树枝阵列以这样的:

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

但它显示“对象的对象”。对于我的目的,我想显示对象的属性,在例如:“intitule”

My array

非常感谢。

回答

1

我建议你写一个自己的Twig extension并添加过滤功能,以它:

1.创建扩展类并添加过滤器名称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.创建服务

根据您的services.yml定义,您可能需要为扩展名创建服务:

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

3.使用视图中的过滤器

,你可以使用它像这样使用过滤器:

var myChart = new Chart(ctx, { 
    type: 'pie', 
    data: { 
     labels: ({{array|chart|raw}}) 
相关问题