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.
Here's my extension:
<?php
// src/OSC/BlogBundle/Twig/BlogsListExtension.php
namespace OSC\BlogBundle\Twig;
class BlogsListExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
'blogsList' => new \Twig_Function_Method($this, array($this, 'blogsList')),
);
}
public function blogsList()
{
$em = $this->getDoctrine()
->getManager();
$repository = $em
->getRepository('OSCBlogBundle:Blog');
$blogs = $repository->findBy(array('visibleState' => true));
usort($blogs, array("\OSC\BlogBundle\Controller\BlogController", "orderBlogByTitle"));
return $blogs;
}
public function getName()
{
return 'osc_BlogsListExtension';
}
}
Here's what I added in my services.yml
services:
osc_blog.blogsList_extension:
class: OSC\BlogBundle\Twig\BlogsListExtension
tags:
- { name: twig.extension }
In my twig template, I want to do the following:
<ul>
{% for blog in blogsList()|sort %}
<li><a href="{{ path('osc_blog_homepage', {'blogId': blog.id })}}"><span>{{ blog.title }}</span></a></li>
{% endfor %}
</ul>
I get the following error:
An exception has been thrown during the compilation of a template ("Notice: Array to string conversion
Finally, my question is how can I pass an array to a variable in order to loop through it in a twig template ?
var_dump($blogs)? Is it an array at all? Also why there is a double sorting? First in the php file (useort) and then another one in for statement.