2016-12-27 77 views
0

所以目前升循環執行JSON數據從數據庫中已經得到了我的控制器:在樹枝

public function indexAction() 
{ 
    $repository = $this->getDoctrine()->getRepository('ApiBundle:Request'); 

    $themes = $repository->findAll(); 

    return $this->render('ApiBundle:Default:index.html.twig', ['themes' => $themes]); 
} 

,並在我的樹枝:

{% for theme in themes %} 
    <div am-col="md-6"> 
     <div am-row> 
      <div am-col="md-3"> 
       {{ theme.preview|json_encode }} 
      </div> 
      <div am-col="md-8"> 
       {{ theme.name }} 
      </div> 
     </div> 
    </div> 
{% endfor %} 

現在theme.previews如下返回一個JSON:

{"icon_with_video_preview":{"icon_url":"https:\/\/0.s3.envato.com\/files\/170231072\/design-wordpress80.png","landscape_url":"https:\/\/0.s3.envato.com\/files\/170231083\/design-wordpresspreview.jpg","video_url":"https:\/\/0.s3.envato.com\/h264-video-previews\/02e0816d-0957-45c4-af2c-792e37bcc37a\/14727479.mp4"}} 

l需要訪問並顯示icon_url。有任何想法嗎? l目前嘗試{{ theme.preview.icon_with_video_preview.icon_url }},但得到一個錯誤,說這個數組不能轉換爲字符串。

+0

您可能想要發佈您使用的確切代碼,實體/實體的確切錯誤和相關部分。 – ccKep

回答

0

您是否嘗試過沿途傾倒不同的東西來查看它是否返回相同的錯誤?

{{ dump(theme.preview) }} 
{{ dump(theme.preview.icon_with_video_preview) }} 
{{ dump(theme.preview.icon_with_video_preview.icon_url) }} 

最終,您可能需要使用樹枝的attribute函數訪問數組鍵。即:

{{ attribute(theme.preview, 'icon_with_video_preview').icon_url }} 

參見:http://twig.sensiolabs.org/doc/functions/attribute.html

1

我認爲這種情況下,你可能需要從控制器發送JSON編碼變量,像這樣:

return $this->render('ApiBundle:Default:index.html.twig',[ 
    'themes' => $themes, 
    'json_themes' => json_encode($themes), 
]); 

然後在你的嫩枝,你可以調用像你需要:

{% for jtheme in json_themes %} 
    {{ jtheme.preview.icon_with_video_preview.icon_url }} 
{% endfor %} 

我包括在控制器中,以防萬一你需要你同時使用json和非json變量。根據需要調整。

讓我們知道這是否有效,我認爲它應該,但你可能需要不同的東西。

+0

你好,開爾文。這是否工作?如果確實如此,可以通過點擊複選標記將其標記爲正確的答案。謝謝! –