Symfony 2 - Twig 模板 - 实体函数结果

Symfony 2 - Twig templates - Entity function results

我正在寻找如何将 symfony2 中实体函数之一返回的值发送到 twig 模板的最佳解决方案。

问题是根据 "How to Handle File Uploads with Doctrine" 手册 (http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html) 连接获取文件 url 上传的文件。我按照最后一个例子 ("Using the id as the Filename").

在控制器中,我得到了 documents 个实体之一。

$document = $this->getDoctrine()->getRepository('AppBundle:Documents')->find($id);

并且我向 twig 模板提供实体详细信息:

return $this->render('AppBundle:Documents:details.html.twig', array('document' => $document));

但是在模板中我需要link到由getAbsolutePath()函数生成的文件。

 public function getAbsolutePath()
    {
        return null === $this->link
            ? null
            : $this->getUploadRootDir().'/'.$this->id.'.'.$this->link;
    }

我可以在控制器中使用以下代码:

return $this->render('AppBundle:Documents:details.html.twig', array('document' => $document, 'link' => $document->getAbsolutePath()));

但是这个解决方案对我来说似乎并不整洁,因为我已经将 $document 发送到 twig。您的实际解决方案是什么?

很简单。在 Twig 模板中,您可以简单地执行以下操作:

{{ document.getAbsolutePath() }}