Symfony 2和twig:在导航中为“当前页面”添加一个类

时间:2013-08-27 11:36:00

标签: symfony twig

所以我在Symfony 2中构建了一个导航菜单,我正试图弄清楚如何让它在当前页面的导航项上显示一个类。我非常擅长PHP,但我在Symfony非常陌生,所以请尽可能做出基本答案。

这是我的代码:

模板

{% 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 %}

导航的两条路线:

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 }

和导航控制器:

 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)
        );
    }

1 个答案:

答案 0 :(得分:3)

在您看来

{% 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 %}