【问题标题】:Looping over json data from your database in twig在 twig 中循环访问数据库中的 json 数据
【发布时间】:2016-12-27 22:37:48
【问题描述】:

所以目前我已经进入了我的控制器:

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

我需要访问和显示 icon_url。有任何想法吗? l 目前尝试{{ theme.preview.icon_with_video_preview.icon_url }},但收到错误提示此数组无法转换为字符串。

【问题讨论】:

  • 您可能想发布您使用的确切代码、确切错误以及实体的相关部分。

标签: php doctrine twig symfony


【解决方案1】:

我认为对于这种情况,您可能需要从控制器发送一个 json 编码的变量,如下所示:

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

然后在您的 Twig 中,您可以根据需要调用:

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

我将两者都包含在控制器中,以防您需要同时使用 json 和非 json 变量。根据需要进行调整。

让我们知道这是否可行,我认为应该可行,但您可能需要一些不同的东西。

【讨论】:

  • 你好,Kelvin。这行得通吗?如果是这样,您能否通过单击复选标记将其标记为正确答案。谢谢!
【解决方案2】:

您是否尝试过转储不同的东西以查看它是否返回相同的错误?

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

最终,您可能需要使用 twig 的 attribute 函数访问数组键。即:

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

见:http://twig.sensiolabs.org/doc/functions/attribute.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2019-01-16
    相关资源
    最近更新 更多