【发布时间】:2015-05-31 19:24:43
【问题描述】:
我正在寻找如何将symfony2 中的一个实体函数返回的值发送到树枝模板的最佳解决方案。
问题是根据“如何使用 Doctrine 处理文件上传”手册 (http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html) 获取上传文件的文件 url。我按照最后一个示例(“使用 id 作为文件名”)。
在控制器中,我得到documents 实体之一。
$document = $this->getDoctrine()->getRepository('AppBundle:Documents')->find($id);
我向树枝模板提供实体详细信息:
return $this->render('AppBundle:Documents:details.html.twig', array('document' => $document));
但是在模板中我需要获得由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。您的实际解决方案是什么?
【问题讨论】:
-
你在哪里定义了
getAbsolutePath()方法?您的Document实体? -
您也可以在 twig 中访问
object(和数组)的所有方法/属性。只需在您的模板中输入{{ document.getAbsolutePath() }} -
解决方案将取决于@Artamiel 问题的答案!同时看看这个例子,如果它有帮助,如果逻辑与模板更相关,大多数人更喜欢创建自定义 Twig 扩展。 Creating a custom twig extension which accepts parameters
-
没有必要为此扩展 twig...正如您在 op 的代码中清楚地看到
getAbsolutePath是一个公共 getter