Answer the question
In order to leave comments, you need to log in
Yii2 how to highlight the active menu item?
Good day colleagues.
Not long ago I began to study the Yii2 framework , and everything seems to be fine, but I can’t get it to correctly highlight (make the active element) the menu.
What we have:
Two tables with a one-to-many relationship.
The first table with the names of the categories (a menu is made from it)
The second article for each category.
In Nav , you need to specify the URL in the form of controller/actions (site/index) which in turn appears in the address bar of the URL.
My array for Nav::Widget();
Array
(
[items] => Array
(
[0] => Array
(
[label] => Главная
[url] => Array
(
[0] => /site/index
)
[linkOptions] => Array
(
[title] => Главная
)
)
[1] => Array
(
[label] => Вело
[url] => Array
(
[0] => /bike
)
[linkOptions] => Array
(
[title] => Вело
)
)
[2] => Array
(
[label] => Авто
[url] => Array
(
[0] => /cars
)
[linkOptions] => Array
(
[title] => Авто
)
)
)
);
Answer the question
In order to leave comments, you need to log in
Why not do it directly on the page using js. The solution is very simple, it seems
In general, I decided so far in this way, let's see how it will prove itself.
public function isActive($alias)
{
$url = $_SERVER["REQUEST_URI"];
//Маршрут по default
if($alias == 'site/index' and $url == '/')
return true;
//Короткие маршруты категорий
if(strpos($url, $alias) !== false)
return true;
else
return false;
}
//Шаблон для вывода меню в виде дерева
private function tplMenu($item)
{
$items = [
[
'label' => $item['name'],
'url' => [$item['alias']],
'linkOptions' => ['title' => $item['title']],
'active'=> $this->isActive($item['alias']),
],
];
if(isset($item['childs']))
{
$label = ['label' => $item['name'],];
foreach ($item['childs'] as $key => $val)
$items['items'][] = ['label' => $val['name'], 'url' => $val['alias'], 'linkOptions' => ['title' => $val['title']],];
$items = array(array_merge($label, $items));
}
return $items;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question