添加活动类以与 sf2 和 twig 链接

发布于 2024-11-02 02:58:01 字数 245 浏览 2 评论 0原文

下面的简单代码:

<li><a href="{{ path('_list') }}">List</a></li>

如果当前页面与 _list 路由匹配,是否有一种简单的方法来添加 class="active"

使用最新的 symfony2 和 twig PR-Release 作为模板引擎

following simple code:

<li><a href="{{ path('_list') }}">List</a></li>

is there a simple way to add an class="active" if the current page matches the _list route?

using the newest PR-Release of symfony2 and twig as template engine

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

谎言月老 2024-11-09 02:58:01

Twig 允许使用条件,并且 Request 对象在整个应用程序中可用。如果您要包含模板,则要获取要使用的路线:

app.request.attributes.get('_route')

如果您正在使用渲染函数,则要使用:

app.request.attributes.get('_internal')

这样,您应该能够使用:

class="{% if app.request.attributes.get('_route') == '_list' %}active{% endif %}"

或更短:

class="{{ app.request.get('_route') == '_list' ? 'active' }}"

Twig allows for conditionals and the Request object is available throughout the application. If you are including the template, to get the route you want to use:

app.request.attributes.get('_route')

If you are using the render function, you want to use:

app.request.attributes.get('_internal')

With that, you should be able to use:

class="{% if app.request.attributes.get('_route') == '_list' %}active{% endif %}"

or shorter:

class="{{ app.request.get('_route') == '_list' ? 'active' }}"
痴情 2024-11-09 02:58:01

有时您不想对路线进行精确匹配。对于这些情况,您可以使用 twig 的“开头为”条件逻辑。

举个例子,假设您正在处理书籍。您有以下路线:book、book_show、book_new、book_edit。您希望在任何这些情况下突出显示导航项 Book。这段代码可以实现这一点。

<a class="{% if app.request.attributes.get('_route') starts with 'book' %}active{% endif %}">Books</a>
<a class="{% if app.request.attributes.get('_route') starts with 'author' %}active{% endif %}">Authors</a>

此示例至少适用于 Symfony 2.3.x

Sometimes you don't want to do exact matching of a route. For those cases, you can use the "starts with" conditional logic of twig.

As an example, lets assume you are working with books. You have the following routes: book, book_show, book_new, book_edit. You want the navigation item Book to be highlighted for any of those cases. This code would accomplish that.

<a class="{% if app.request.attributes.get('_route') starts with 'book' %}active{% endif %}">Books</a>
<a class="{% if app.request.attributes.get('_route') starts with 'author' %}active{% endif %}">Authors</a>

This example works with at least Symfony 2.3.x

笑脸一如从前 2024-11-09 02:58:01

最短版本:

{% set route = app.request.get('_route') %}

 <li class="{{ route starts with 'post' ? 'open' }}"></li>
 <li class="{{ route starts with 'category' ? 'open' }}"></li>

有时有用:

{% set route = app.request.get('_route') %}

<li class="{{ 'post' in route ? 'open' }}"></li>
<li class="{{ 'category' in route ? 'open' }}"></li>

Shortest version:

{% set route = app.request.get('_route') %}

 <li class="{{ route starts with 'post' ? 'open' }}"></li>
 <li class="{{ route starts with 'category' ? 'open' }}"></li>

Sometimes useful:

{% set route = app.request.get('_route') %}

<li class="{{ 'post' in route ? 'open' }}"></li>
<li class="{{ 'category' in route ? 'open' }}"></li>
月依秋水 2024-11-09 02:58:01

使用三元运算符:

    {% set route = app.request.attributes.get('_route') %}
    <ul class="nav navbar-nav">
        <li {{ route ==  'profile_index' ? 'class="active"' }}><a href="{{ path('profile_index') }}"><i class="icon-profile position-left"></i> My Profile</a></li>
        <li {{ route ==  'influencers_index' ? 'class="active"'}}><a href="{{ path('influencers_index') }}"><i class="icon-crown position-left"></i> Influencers</a></li>
        <li {{ route ==  'task_manager_index' ? 'class="active"'}}><a href="{{ path('task_manager_index') }}"><i class="icon-alarm-check position-left"></i> Task Manager</a></li>
    </ul>

With ternary operator:

    {% set route = app.request.attributes.get('_route') %}
    <ul class="nav navbar-nav">
        <li {{ route ==  'profile_index' ? 'class="active"' }}><a href="{{ path('profile_index') }}"><i class="icon-profile position-left"></i> My Profile</a></li>
        <li {{ route ==  'influencers_index' ? 'class="active"'}}><a href="{{ path('influencers_index') }}"><i class="icon-crown position-left"></i> Influencers</a></li>
        <li {{ route ==  'task_manager_index' ? 'class="active"'}}><a href="{{ path('task_manager_index') }}"><i class="icon-alarm-check position-left"></i> Task Manager</a></li>
    </ul>
俯瞰星空 2024-11-09 02:58:01

这是使用 symfony 3.4 完成的,但可能可以使用 SF2 完成类似的操作。

src\AppBundle\Twig\AppExtension.php

<?php

namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\RequestStack;

class AppExtension extends \Twig_Extension
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('activeMenu', [$this, 'activeMenu'])
        ];
    }

    /**
     * Pass route names. If one of route names matches current route, this function returns
     * 'active'
     * @param array $routesToCheck
     * @return string
     */
    public function activeMenu(array $routesToCheck)
    {
        $currentRoute = $this->requestStack->getCurrentRequest()->get('_route');

        foreach ($routesToCheck as $routeToCheck) {
            if ($routeToCheck == $currentRoute) {
                return 'active';
            }
        }

        return '';
    }
}

将其添加到 services.yml

services:
    #... some other services
    AppBundle\Twig\AppExtension:
        arguments: ["@request_stack"]

用法:

<ul class="nav navbar-nav">
    <li class="{{ activeMenu(['form', 'edit_form']) }}"><a href="{{ path('form') }}">Form</a></li>
    <li class="{{ activeMenu(['list']) }}"><a href="{{ path('list') }}">List</a></li>
</ul>

This is done with symfony 3.4, but probably something similar can be done with SF2.

src\AppBundle\Twig\AppExtension.php

<?php

namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\RequestStack;

class AppExtension extends \Twig_Extension
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('activeMenu', [$this, 'activeMenu'])
        ];
    }

    /**
     * Pass route names. If one of route names matches current route, this function returns
     * 'active'
     * @param array $routesToCheck
     * @return string
     */
    public function activeMenu(array $routesToCheck)
    {
        $currentRoute = $this->requestStack->getCurrentRequest()->get('_route');

        foreach ($routesToCheck as $routeToCheck) {
            if ($routeToCheck == $currentRoute) {
                return 'active';
            }
        }

        return '';
    }
}

Add this to services.yml

services:
    #... some other services
    AppBundle\Twig\AppExtension:
        arguments: ["@request_stack"]

Usage:

<ul class="nav navbar-nav">
    <li class="{{ activeMenu(['form', 'edit_form']) }}"><a href="{{ path('form') }}">Form</a></li>
    <li class="{{ activeMenu(['list']) }}"><a href="{{ path('list') }}">List</a></li>
</ul>
似梦非梦 2024-11-09 02:58:01

我找到了一个非常好的捆绑包,可以自动处理所有这些东西:

https://github.com/KnpLabs/KnpMenuBundle

i found a very good Bundle that handles all this stuff automagically:

https://github.com/KnpLabs/KnpMenuBundle

一杆小烟枪 2024-11-09 02:58:01

SF2.2

{{ dump(app.request.server.get('PATH_INFO')) }}

SF2.2

{{ dump(app.request.server.get('PATH_INFO')) }}
晚雾 2024-11-09 02:58:01

Symfony2.3,在Twig中,尝试这样获取uri:

{{ dump(app.request.server.get("REQUEST_URI")) }}

Symfony2.3, in Twig, try this to get uri:

{{ dump(app.request.server.get("REQUEST_URI")) }}
亽野灬性zι浪 2024-11-09 02:58:01

我发现更有效地了解我们是否位于活动页面和链接上:

在文件 xx.html.twig 中:
在你的头文件中

{% set route_name = app.request.attributes.get('_route') %}

并添加 twig 的 html 类

{% if route_name matches '{^issue}' %}active{% endif %}

I found more efficient to know if we are on the active page and the link or not:

in file xx.html.twig :
In on your header file

{% set route_name = app.request.attributes.get('_route') %}

And add in html class of twig

{% if route_name matches '{^issue}' %}active{% endif %}
又爬满兰若 2024-11-09 02:58:01

这就是我的做法(使用 Symfony 2.6)

<li {% if app.request.get('_route') == '_homepage' %} class="active" {% endif %}><a href="{{ path('_homepage') }}">Student</a></li>

'_homepage' 是你的包的 routing.yml 中的路由名称,路由看起来像这样

_homepage:
    path:     /
    defaults: { _controller: CoreBundle:Default:index }

This is how I do it (using Symfony 2.6)

<li {% if app.request.get('_route') == '_homepage' %} class="active" {% endif %}><a href="{{ path('_homepage') }}">Student</a></li>

'_homepage' is the name of route in routing.yml of your bundle and the route looks like this

_homepage:
    path:     /
    defaults: { _controller: CoreBundle:Default:index }
笑咖 2024-11-09 02:58:01

class="class_name {% ifloop.index0 == 0 %}CLASSNAME{% endif %}"

class="class_name {% if loop.index0 == 0 %}CLASSNAME{% endif %}"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文