Note that there are some explanatory texts on larger screens.

plurals
  1. POSymfony2 - Twig Function returning an array
    primarykey
    data
    text
    <p>I created a twig extension that returns me the list of all the blogs I have. This list is an array that I loop through in my twig template.</p> <p><strong>Here's my extension:</strong> </p> <pre><code>&lt;?php // src/OSC/BlogBundle/Twig/BlogsListExtension.php namespace OSC\BlogBundle\Twig; class BlogsListExtension extends \Twig_Extension { public function getFunctions() { return array( 'blogsList' =&gt; new \Twig_Function_Method($this, array($this, 'blogsList')), ); } public function blogsList() { $em = $this-&gt;getDoctrine() -&gt;getManager(); $repository = $em -&gt;getRepository('OSCBlogBundle:Blog'); $blogs = $repository-&gt;findBy(array('visibleState' =&gt; true)); usort($blogs, array("\OSC\BlogBundle\Controller\BlogController", "orderBlogByTitle")); return $blogs; } public function getName() { return 'osc_BlogsListExtension'; } } </code></pre> <p><strong>Here's what I added in my services.yml</strong></p> <pre><code>services: osc_blog.blogsList_extension: class: OSC\BlogBundle\Twig\BlogsListExtension tags: - { name: twig.extension } </code></pre> <p><strong>In my twig template, I want to do the following:</strong></p> <pre><code>&lt;ul&gt; {% for blog in blogsList()|sort %} &lt;li&gt;&lt;a href="{{ path('osc_blog_homepage', {'blogId': blog.id })}}"&gt;&lt;span&gt;{{ blog.title }}&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p><strong>I get the following error:</strong></p> <blockquote> <p>An exception has been thrown during the compilation of a template ("Notice: Array to string conversion</p> </blockquote> <p><strong>Finally, my question is how can I pass an array to a variable in order to loop through it in a twig template ?</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload