2015-11-25 43 views
1

我有字段類型Symfony的學說可見在枝條

/** 
* @var array 
* 
* @ORM\Column(name="raw", type="json_array", nullable=true) 
*/ 
private $raw; 

和予置在該日提交的數據格式JSON

$jsonRaw = array(
        'repository_language' => $repository['language'], 
        'used_languages' => $languages, 
        'commits' => $commits, 
        'scooped_branch' => $sha, 
        'first_commit' => empty($this->committer[0]['author']) ? null : $this->committer[0], 
        'last_commit' => empty($this->committer[1]['author']) ? null : $this->committer[1] 
       ); 

和在實體設置

$entity->setRaw(json_encode($jsonRaw)); 

,然後我有這個字段中的數據field_data和我在模板中渲染此字段,但有錯誤

   {% for languages in project.raw.used_languages|json_decode %} 
        <div class="row col-sm-2" style="position: relative; text-align: center; margin: 0; padding: 0;"> 
         <small style="color: #00312f;"> 
          <strong>{{ languages.lang }}</strong>:<br> 
          {{ languages.percent|round(1, 'floor') }}%<br> 
         </small> 
        </div> 
       {% endfor %} 

Impossible to access an attribute ("used_languages") on a string variable ("{"repository_language":"PHP","used_languages":[{"lang":"PHP","percent..... 

爲什麼?我這個也許小枝沒有朋友用JSON和創建自定義的樹枝過濾

class VarsExtension extends Twig_Extension 
{ 
protected $container; 

public function __construct(ContainerInterface $container) 
{ 
    $this->container = $container; 
} 

public function getName() 
{ 
    return 'some.extension'; 
} 

public function getFilters() { 
    return array(
     'json_decode' => new \Twig_Filter_Method($this, 'jsonDecode'), 
    ); 
} 

public function jsonDecode($str) { 
    return json_decode($str); 
} 
} 

,並嘗試使用

   {% for languages in project.raw.used_languages|json_decode %} 
        <div class="row col-sm-2" style="position: relative; text-align: center; margin: 0; padding: 0;"> 
         <small style="color: #00312f;"> 
          <strong>{{ languages.lang }}</strong>:<br> 
          {{ languages.percent|round(1, 'floor') }}%<br> 
         </small> 
        </div> 
       {% endfor %} 

,仍然有錯誤

Impossible to access an attribute ("used_languages") on a string variable ("{"repository_language":"PHP","used_languages":[{"lang":"PHP","percent":75.976812123425},{"lang":"JavaScript","percent":13.194136518949},{"lang":"CSS","percent":10.829051357625}], 

幫助請,我沒有想法(

+0

在通過鍵訪問元素之前應用過濾器json_decode – Matteo

+3

{%set raw = project.raw | json_decode%} {{raw.used_languages}} – Snoozer

+0

Snoozer:thnks非常匹配 –

回答

1

您可以簡單地應用過濾器json_decode,然後按鍵訪問元素,例如@Snoozer示例:

{% set raw = project.raw | json_decode %} {{ raw.used_languages }}