Reputation: 1964
So I've built a navigation menu in Symfony 2 and i'm trying to work out how to get it to display a class on the nav item of the current page. I'm pretty good at PHP but I'm very new at Symfony so please make your answers as basic as possible.
Here is my code:
Template:
{% for nav in navItems %}
<li>
<a title="{{ nav.pageName }}" {% //Logic to display class %} class="" {% //endlogic %} href="{{ path('myclient_style_guide_page_elements_show', {'pageUrl': nav.pageUrl}) }}">{{ nav.pageName }}</a>
</li>
{% endfor %}
The two routes for the navigation:
myClient_style_guide_page_elements_show:
pattern: /page-elements/{pageUrl}
defaults: { _controller: myClientStyleGuideBundle:pageElements:show}
requirements:
_method: GET
myClient_style_guide_page_elements_nav:
pattern: /page-elements-nav
defaults: { _controller: myClientStyleGuideBundle:pageElements:nav }
and the controller for the navigation:
public function navAction()
{
$em = $this->getDoctrine()->getManager();
$navItems = $em->getRepository('myClientStyleGuideBundle:pageElements')->findBypageParent('page-elements');
if (!$navItems) throw $this->createNotFoundException('Unable to find any pages under this category');
return $this->render(
'myClientStyleGuideBundle:Partial:peNav.html.twig',
array('navItems' => $navItems)
);
}
Upvotes: 2
Views: 2636
Reputation: 8915
in your view:
{% macro is_current_route(route) %}
{%- if app.request.attributes.get('_route') == route -%}
{{- 'class="active"' -}} {%- else -%} {{- 'class="inactive"' -}}
{%- endif -%}
{% endmacro %}
{% import _self as croute %}
{% for nav in navItems %}
<li>
<a title="{{ nav.pageName }}"
{{- croute.is_current_route('myclient_style_guide_page_elements_show') -}}
href="{{ path('myclient_style_guide_page_elements_show', {'pageUrl': nav.pageUrl}) }}"
>
{{ nav.pageName }}
</a>
</li>
{% endfor %}
Upvotes: 3