Reputation: 868
I created a small website with 4 pages, means 4 navigation points. There is always one of these navigation points set as active in css:
class="active"
All these 4 pages inherit the layout.html.twig file where the navigation is defined. Which is the easiest way to change the class ("active") class depending on the navigation point choosen?
Thanks in advance for your help!
Upvotes: 0
Views: 4778
Reputation: 442
You could define the current menu entry:
{% set current_menu = "home" %}
And then check what the current menu entry is:
<li class="nav-item{% if current_menu is same as("home") %} active{% endif %}">
Upvotes: 0
Reputation: 2570
You can use the KnpMenuBundle. For example in src/Foo/BarBundle/Menu/MenuBuilder.php
:
<?php
namespace Foo\BarBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\HttpFoundation\Request;
class MenuBuilder
{
private $factory;
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createMyMenu(Request $request)
{
$menu = $this->factory->createItem('root');
$menu->setChildrenAttributes(array('class' => 'my-menu'));
// Always visible
$menu->addChild('Home', array('route' => 'foo_bar_homepage'));
// According to the current route
switch($request->get('_route')) {
case 'item_list':
$menu->addChild('Items')
->setCurrent(true);
break;
case 'item_show':
$menu->addChild('Items', array('route' => 'item_list'));
$menu->addChild('Show')
->setCurrent(true);
break;
// ...
}
}
The active class will be available automatically when calling setCurrent()
method.
The documentation is available here, and you can find another tutorial here.
Upvotes: 3
Reputation: 868
As I don't have that many navigation points I solved the problem with a if tag of twig.
<a href="{{ path('dbe_underConstruction') }}" title="Home"
{% if app.request.get('_route') == 'dbe_underConstruction' %} class="active"{% endif %}>Home </a>
This might be not that a clear solution, but it works fine :-)
Upvotes: 3