Reputation: 545
I'm new to Symfony2 (with knowledge in 1.2-1.4) and having little trouble trying to fetch some objects from the DB. I have a base template (index.html.twig) which have the following code block:
<nav>
<ul class="menu">
<li><a class="active" href="index.html">Home Page</a></li>
{% for category in categories %}
<li><a href="{{ category.name }}">{{ category.name }}</a></li>
{% endfor %}
<li class="last-item"><a href="contacts.html">Contact Us</a></li>
</ul>
</nav>
The method fetching categories is inside DefaultController:
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$categories = $em->getRepository('XxxYyyBundle:Category')->findAll();
$genres = $em->getRepository('XxxYyyBundle:Genre')->findAll();
echo $categories.$genres;
return array('categories' => $categories, 'genres' => $genres);
}
If I access the page from Default it works perfectly, but if I try to access from another page that extends the template (using {% extends "XxxYyyBundle:Default:index.html.twig" %}) I get the following error:
Variable "categories" does not exist in XxxYyyBundle:Default:index.html.twig at line 53
I tried all the options included in the book (% include, etc) with the only conclusion that from another pages indexAction() is not executed. I think that fetching items from the DB to include them in a menu is something usual, so if someone is familiar to this matter I'll be very grateful for any help.
Thanks.
Upvotes: 1
Views: 440
Reputation: 8965
The easiest way is to place a render tag in your layout and reference a controller that runs the queries and renders the menu fragment.
{% render 'SomeBundle:Menu:menu' %}
Upvotes: 1