2

所以我在 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)
        );
    }
4

1 回答 1

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 %}
于 2013-08-27T11:44:38.613 回答