dodaj active class do linku z sf2 i twig

Po prostym kodzie:

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

Czy istnieje prosty sposób na dodanie class="active" Jeśli bieżąca strona pasuje do trasy _list?

Używanie najnowszej PR-wersji symfony2 i twig jako silnika szablonów

Author: j0k, 2011-04-18

10 answers

Twig pozwala na warunkowe i obiekt Request jest dostępny w całej aplikacji. Jeśli dołączasz szablon, aby uzyskać trasę, której chcesz użyć:

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

Jeśli używasz funkcji render, chcesz użyć:

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

Z tym powinieneś być w stanie użyć:

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

Lub krótszy:

class="{{ app.request.get('_route') == '_list' ? 'active' }}"
 80
Author: Tau_Zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 21:36:21

Czasami nie chcesz dokładnie dopasować trasy. W takich przypadkach możesz użyć logiki warunkowej "zaczyna się od" gałązki.

Jako przykład, załóżmy, że pracujesz z książkami. Masz następujące trasy: book, book_show, book_new, book_edit. Chcesz, aby książka pozycji nawigacyjnych była podświetlona w każdym z tych przypadków. Ten kod by tego dokonał.

<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>

Ten przykład działa z co najmniej Symfony 2.3.x

 18
Author: John Kramlich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-21 22:16:17

Najkrótsza wersja:

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

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

Czasami przydatne:

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

<li class="{{ 'post' in route ? 'open' }}"></li>
<li class="{{ 'category' in route ? 'open' }}"></li>
 13
Author: Max Lipsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 10:08:37

Z operatorem trójdzielnym:

    {% 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>
 8
Author: Yuriy Korman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-18 23:01:44

Znalazłem bardzo dobry pakiet, który obsługuje wszystkie te rzeczy automagicznie:

Https://github.com/KnpLabs/KnpMenuBundle

 3
Author: choise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-08 17:54:39

SF2.2

{{ dump(app.request.server.get('PATH_INFO')) }}
 1
Author: Karol Gontarski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-03 18:17:50

Symfony2. 3, w gałązce, spróbuj to uzyskać uri:

{{ dump(app.request.server.get("REQUEST_URI")) }}
 1
Author: Degas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-16 06:12:12

Tak to robię (używając Symfony 2.6)

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

'_homepage' jest to nazwa trasy w routing.yml Twojego zestawu i trasa wygląda tak:

_homepage:
    path:     /
    defaults: { _controller: CoreBundle:Default:index }
 0
Author: Baig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-08 11:22:12

Robi się to za pomocą symfony 3.4, ale prawdopodobnie coś podobnego można zrobić za pomocą 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 '';
    }
}

Dodaj to do usług.yml

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

Użycie:

<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>
 0
Author: Darius.V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-07 11:31:04

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

 -2
Author: Marcin Łęża,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-03 12:47:57