Menu
API reference › yii › widgets › Menu
Menu displays a multi-level menu using nested HTML lists.
The main property of Menu is $items, which specifies the possible items in the menu.
A menu item can contain sub-items which specify the sub-menu under that menu item.
Menu checks the current route and request parameters to toggle certain menu items with active state.
Note that Menu only renders the HTML tags about the menu. It does not do any styling. You are responsible to provide CSS styles to make it look like a real menu.
The following example shows how to use Menu:
echo Menu::widget([ 'items' => [ // Important: you need to specify url as 'controller/action', // not just as 'controller' even if default action is used. ['label' => 'Home', 'url' => ['site/index']], // 'Products' menu item will be selected as long as the route is 'product/index' ['label' => 'Products', 'url' => ['product/index'], 'items' => [ ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']], ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']], ]], ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest], ],]);Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$activateItems | bool | Whether to automatically activate items according to whether their route setting matches the currently requested route. Default: true. | Menu |
$activateParents | bool | Whether to activate parent menu items when one of the corresponding child menu items is active. Default: false. | Menu |
$activeCssClass | string | The CSS class to be appended to the active menu item. Default: 'active'. | Menu |
$autoIdPrefix static | string | The prefix to the automatically generated widget IDs. Default: 'w'. | yii\ |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$encodeLabels | bool | Whether the labels for menu items should be HTML-encoded. Default: true. | Menu |
$firstItemCssClass | string| | The CSS class that will be assigned to the first item in the main menu or each submenu. Default: null. | Menu |
$hideEmptyItems | bool | Whether to hide empty menu items. Default: true. | Menu |
$id | string | Id of the widget. | yii\ |
$itemOptions | array | List of HTML attributes shared by all menu $items. Default: []. | Menu |
$items | array | List of menu items. Default: []. | Menu |
$labelTemplate | string | The template used to render the body of a menu which is NOT a link. Default: '{label}'. | Menu |
$lastItemCssClass | string| | The CSS class that will be assigned to the last item in the main menu or each submenu. Default: null. | Menu |
$linkTemplate | string | The template used to render the body of a menu which is a link. Default: '<a href="{url}">{label}</a>'. | Menu |
$options | array | The HTML attributes for the menu’s container tag. Default: []. | Menu |
$params | array| | The parameters used to determine if a menu item is active or not. Default: null. | Menu |
$route | string| | The route used to determine if a menu item is active or not. Default: null. | Menu |
$submenuTemplate | string | The template used to render a list of sub-menus. Default: "\. | Menu |
$view | yii\ | The view object that can be used to render views or view files. | yii\ |
$viewPath read-only | string | The directory containing the view files for this widget. | yii\ |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
afterRun() | This method is invoked right after a widget is executed. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
beforeRun() | This method is invoked right before the widget is executed. | yii\ |
begin() static | Begins a widget. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
end() static | Ends a widget. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getId() | Returns the ID of the widget. | yii\ |
getView() | Returns the view object that can be used to render views or view files. | yii\ |
getViewPath() | Returns the directory containing the view files for this widget. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | yii\ |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
render() | Renders a view. | yii\ |
renderFile() | Renders a view file. | yii\ |
run() | Renders the menu. | Menu |
setId() | Sets the ID of the widget. | yii\ |
setView() | Sets the view object to be used by this widget. | yii\ |
trigger() | Triggers an event. | yii\ |
widget() static | Creates a widget instance and runs it. | yii\ |
isItemActive() protected | Checks whether a menu item is active. | Menu |
normalizeItems() protected | Normalizes the $items property to remove invisible items and activate certain items. | Menu |
renderItem() protected | Renders the content of a menu item. | Menu |
renderItems() protected | Recursively renders the menu items (without the container tag). | Menu |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_INIT | yii\ | An event that is triggered when the widget is initialized via init(). Event name: 'init'. Available since 2.0.11. | yii\ |
EVENT_BEFORE_RUN | yii\ | An event raised right before executing a widget. Event name: 'beforeRun'. Available since 2.0.11. | yii\ |
EVENT_AFTER_RUN | yii\ | An event raised right after executing a widget. Event name: 'afterRun'. Available since 2.0.11. | yii\ |
Property details
Section titled “Property details”$activateParents
Section titled “$activateParents ”public bool $activateParents = falseWhether to activate parent menu items when one of the corresponding child menu items is active.
The activated parent menu items will also have its CSS classes appended with $activeCssClass.
$firstItemCssClass
Section titled “$firstItemCssClass ”public string|null $firstItemCssClass = nullThe CSS class that will be assigned to the first item in the main menu or each submenu.
Defaults to null, meaning no such CSS class will be assigned.
$hideEmptyItems
Section titled “$hideEmptyItems ”public bool $hideEmptyItems = trueWhether to hide empty menu items.
An empty menu item is one whose url option is not
set and which has no visible child menu items.
$itemOptions
Section titled “$itemOptions ”public array $itemOptions = []List of HTML attributes shared by all menu $items.
If any individual menu item
specifies its options, it will be merged with this property before being used to generate the HTML
attributes for the menu item tag. The following special options are recognized:
- tag: string, defaults to “li”, the tag name of the item container tags.
Set to false to disable container tag.
See also
Html::tag().
$items
Section titled “$items ”public array $items = []List of menu items.
Each menu item should be an array of the following structure:
- label: string, optional, specifies the menu item label. When
$encodeLabelsis true, the label will be HTML-encoded. If the label is not specified, an empty string will be used. - encode: boolean, optional, whether this item
s label should be HTML-encoded. This param will override global [$encodeLabels`](Menu.md#property-encodeLabels) param. - url: string or array, optional, specifies the URL of the menu item. It will be processed by
Url::to(). When this is set, the actual menu item content will be generated using$linkTemplate; otherwise,$labelTemplatewill be used. - visible: boolean, optional, whether this menu item is visible. Defaults to true.
- items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.
- active: boolean or Closure, optional, whether this menu item is in active state (currently selected).
When using a closure, its signature should be
function ($item, $hasActiveChild, $isItemActive, $widget). Closure must returntrueif item should be marked asactive, otherwise -false. If a menu item is active, its CSS class will be appended with$activeCssClass. If this option is not set, the menu item will be set active automatically when the current request is triggered byurl. For more details, please refer toisItemActive(). - template: string, optional, the template used to render the content of this menu item.
The token
{url}will be replaced by the URL associated with this menu item, and the token{label}will be replaced by the label of the menu item. If this option is not set,$linkTemplateor$labelTemplatewill be used instead. - submenuTemplate: string, optional, the template used to render the list of sub-menus.
The token
{items}will be replaced with the rendered sub-menu items. If this option is not set,$submenuTemplatewill be used instead. - options: array, optional, the HTML attributes for the menu container tag.
$labelTemplate
Section titled “$labelTemplate ”public string $labelTemplate = '{label}'The template used to render the body of a menu which is NOT a link.
In this template, the token {label} will be replaced with the label of the menu item.
This property will be overridden by the template option set in individual menu items via $items.
$lastItemCssClass
Section titled “$lastItemCssClass ”public string|null $lastItemCssClass = nullThe CSS class that will be assigned to the last item in the main menu or each submenu.
Defaults to null, meaning no such CSS class will be assigned.
$linkTemplate
Section titled “$linkTemplate ”public string $linkTemplate = '<a href="{url}">{label}</a>'The template used to render the body of a menu which is a link.
In this template, the token {url} will be replaced with the corresponding link URL;
while {label} will be replaced with the link text.
This property will be overridden by the template option set in individual menu items via $items.
$options
Section titled “$options ”public array $options = []The HTML attributes for the menu’s container tag.
The following special options are recognized:
- tag: string, defaults to “ul”, the tag name of the item container tags. Set to false to disable container tag.
See also
Html::tag().
$params
Section titled “$params ”public array|null $params = nullThe parameters used to determine if a menu item is active or not.
If not set, it will use $_GET.
$route
Section titled “$route ”public string|null $route = nullThe route used to determine if a menu item is active or not.
If not set, it will use the route of the current request.
$submenuTemplate
Section titled “$submenuTemplate ”public string $submenuTemplate = "\n<ul>\n{items}\n</ul>\n"The template used to render a list of sub-menus.
In this template, the token {items} will be replaced with the rendered sub-menu items.
Method details
Section titled “Method details”isItemActive()
Section titled “isItemActive() ”protected function isItemActive(array $item): boolChecks whether a menu item is active.
This is done by checking if $route and $params match that specified in the url option of the menu item.
When the url option of a menu item is specified in terms of an array, its first element is treated
as the route for the item and the rest of the elements are the associated parameters.
Only when its route and parameters match $route and $params, respectively, will a menu item
be considered active.
Parameters
| Parameter | Type | Description |
|---|---|---|
$item | array | The menu item to be checked |
Returns
bool: Whether the menu item is active
normalizeItems()
Section titled “normalizeItems() ”protected function normalizeItems(array $items, bool &$active): arrayNormalizes the $items property to remove invisible items and activate certain items.
Parameters
| Parameter | Type | Description |
|---|---|---|
$items | array | The items to be normalized. |
$active | bool | Whether there is an active child menu item. |
Returns
array: The normalized menu items
renderItem()
Section titled “renderItem() ”protected function renderItem(array $item): stringRenders the content of a menu item.
Note that the container and the sub-menus are not rendered here.
Parameters
| Parameter | Type | Description |
|---|---|---|
$item | array | The menu item to be rendered. Please refer to $items to see what data might be in the item. |
Returns
string: The rendering result
renderItems()
Section titled “renderItems() ”protected function renderItems(array $items): stringRecursively renders the menu items (without the container tag).
Parameters
| Parameter | Type | Description |
|---|---|---|
$items | array | The menu items to be rendered recursively |
Returns
string: The rendering result