【问题标题】:How do I call an Entity method from Twig如何从 Twig 调用实体方法
【发布时间】:2016-07-22 22:52:07
【问题描述】:

你们中的很多人会告诉我,我应该想办法在我的表中更好地建立关系,但是我有一个“products”表和一个“product_images”表,它们很容易在查询中加入,但是因为图像的路径可能完全不同,我不想在表中存储路径名称,我需要一个函数来进行一些计算以找出路径是什么。我需要为每个产品运行该方法,因为我正在迭代每个产品以获取图像的路径。

我想做的,也许我的想法不正确,是在 Twig 中我想请求一种方法来为产品实体运行

{% for product in products %}
    {{product.getImageUrl()}}
{% endfor %}

这会在我的产品实体中调用一个方法

//AppBundle:Entity:Product
public function getImageUrl()
{
    $repository = $this->getDoctrine()->getRepository('AppBundle:Product');
    return $repository->getImagePath($this->id);
}

在我的存储库中:

//AppBundle:Repositiories:ProductRepository
public function getImagePath($id)
{
    return 'http://domain.com/path/to/image.jpg'//simplified for my question
}

我该怎么做?当我现在尝试这个时,我收到以下错误:

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in product/index.html.twig at line 19. 

第 19 行在哪里

<img src="{{product.getImageUrl()}}" alt="img">

如何使用实体中的方法来完成?或者告诉我我还能怎么做。提前致谢。

【问题讨论】:

  • 你真的应该弄清楚如何更好地处理你的关系。只是在开玩笑。你的树枝是正确的。让 Product::getImageUrl() 返回一个简单的字符串来证明它。你的产品实体都搞砸了。您无法在其中访问容器。您可能需要 ProductImagManager::getImageUrl($product) 之类的东西,然后通过 twig 扩展在 twig 中访问它。我假设您实际上传递的是产品实体数组而不是产品数组数组。您的错误消息似乎表明了这一点。
  • {{ product.imageUrl }} ?

标签: symfony doctrine-orm twig


【解决方案1】:

您的问题的答案就在错误消息中。 正如它向您解释的那样,twig 无法将数组转换为字符串。现在为什么我们还有一个数组?

我假设,在您的 public function getImagePath($id) 方法中,您最终调用 getResult() 以获得所需的图像路径。然而,getResult 总是返回一个结果数组,即使只有一个结果。

如果您确定只会得到一个结果,请尝试致电getOneOrNullResult(),这应该可以解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多