在树枝
问题描述:
所以目前升循环执行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 }}
,但得到一个错误,说这个数组不能转换为字符串。
答
您是否尝试过沿途倾倒不同的东西来查看它是否返回相同的错误?
{{ 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 }}
答
我认为这种情况下,你可能需要从控制器发送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
你好,开尔文。这是否工作?如果确实如此,可以通过点击复选标记将其标记为正确的答案。谢谢! –
您可能想要发布您使用的确切代码,实体/实体的确切错误和相关部分。 – ccKep