0
votes

I am looking for best solution how to send value returned by one of entity function's in symfony2 to twig template.

The problem is connecting with getting file url for file uploaded according to "How to Handle File Uploads with Doctrine" manual (http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html). I was following the last example ("Using the id as the Filename").

In controller I am getting one of documents entity.

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

and I provide entity details to twig template:

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

However in the template I need to get link to the file which is generated by getAbsolutePath() function.

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

I may use in controller the following code:

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

but this solution does not seems to tidy for me, as I am already sending $document to twig. What would be your practical solution?

1
Where did you define getAbsolutePath() method to? Your Document entity?Artamiel
You can access all methods/attributes of an object (and arrays) in twig as well. Just do {{ document.getAbsolutePath() }} in your templateDarkBee
The solution would depend on the answer to @Artamiel question! Meanwhile look into this example, if it helps cos the most people prefer to create custom Twig extensions if the logic is more related to templates. Creating a custom twig extension which accepts parametersBentCoder
There is no need to extend twig for this... As you clearly see out of op's code that getAbsolutePath is a public getterDarkBee

1 Answers

2
votes

Its simple. In a Twig template you can simply do:

{{ document.getAbsolutePath() }}