Skip to content
PHP Ecosystem
Explore

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],
],
]);
PropertyTypeDescriptionDefined by
$activateItemsboolWhether to automatically activate items according to whether their route setting matches the currently requested route. Default: true.Menu
$activateParentsboolWhether to activate parent menu items when one of the corresponding child menu items is active. Default: false.Menu
$activeCssClassstringThe CSS class to be appended to the active menu item. Default: 'active'.Menu
$autoIdPrefix staticstringThe prefix to the automatically generated widget IDs. Default: 'w'.yii\base\Widget
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$encodeLabelsboolWhether the labels for menu items should be HTML-encoded. Default: true.Menu
$firstItemCssClassstring|nullThe CSS class that will be assigned to the first item in the main menu or each submenu. Default: null.Menu
$hideEmptyItemsboolWhether to hide empty menu items. Default: true.Menu
$idstringId of the widget.yii\base\Widget
$itemOptionsarrayList of HTML attributes shared by all menu $items. Default: [].Menu
$itemsarrayList of menu items. Default: [].Menu
$labelTemplatestringThe template used to render the body of a menu which is NOT a link. Default: '{label}'.Menu
$lastItemCssClassstring|nullThe CSS class that will be assigned to the last item in the main menu or each submenu. Default: null.Menu
$linkTemplatestringThe template used to render the body of a menu which is a link. Default: '<a href="{url}">{label}</a>'.Menu
$optionsarrayThe HTML attributes for the menu’s container tag. Default: [].Menu
$paramsarray|nullThe parameters used to determine if a menu item is active or not. Default: null.Menu
$routestring|nullThe route used to determine if a menu item is active or not. Default: null.Menu
$submenuTemplatestringThe template used to render a list of sub-menus. Default: "\n<ul>\n{items}\n</ul>\n".Menu
$viewyii\web\ViewThe view object that can be used to render views or view files.yii\base\Widget
$viewPath read-onlystringThe directory containing the view files for this widget.yii\base\Widget
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
afterRun()This method is invoked right after a widget is executed.yii\base\Widget
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
beforeRun()This method is invoked right before the widget is executed.yii\base\Widget
begin() staticBegins a widget.yii\base\Widget
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
end() staticEnds a widget.yii\base\Widget
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getId()Returns the ID of the widget.yii\base\Widget
getView()Returns the view object that can be used to render views or view files.yii\base\Widget
getViewPath()Returns the directory containing the view files for this widget.yii\base\Widget
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.yii\base\Widget
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
render()Renders a view.yii\base\Widget
renderFile()Renders a view file.yii\base\Widget
run()Renders the menu.Menu
setId()Sets the ID of the widget.yii\base\Widget
setView()Sets the view object to be used by this widget.yii\base\Widget
trigger()Triggers an event.yii\base\Component
widget() staticCreates a widget instance and runs it.yii\base\Widget
isItemActive() protectedChecks whether a menu item is active.Menu
normalizeItems() protectedNormalizes the $items property to remove invisible items and activate certain items.Menu
renderItem() protectedRenders the content of a menu item.Menu
renderItems() protectedRecursively renders the menu items (without the container tag).Menu
EventTypeDescriptionDefined by
EVENT_INITyii\base\EventAn event that is triggered when the widget is initialized via init(). Event name: 'init'. Available since 2.0.11.yii\base\Widget
EVENT_BEFORE_RUNyii\base\WidgetEventAn event raised right before executing a widget. Event name: 'beforeRun'. Available since 2.0.11.yii\base\Widget
EVENT_AFTER_RUNyii\base\WidgetEventAn event raised right after executing a widget. Event name: 'afterRun'. Available since 2.0.11.yii\base\Widget
public bool $activateParents = false

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

public string|null $firstItemCssClass = null

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

public bool $hideEmptyItems = true

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

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().
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 $encodeLabels is true, the label will be HTML-encoded. If the label is not specified, an empty string will be used.
  • encode: boolean, optional, whether this items 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, $labelTemplate will 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 return true if item should be marked as active, 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 by url. For more details, please refer to isItemActive().
  • 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, $linkTemplate or $labelTemplate will 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, $submenuTemplate will be used instead.
  • options: array, optional, the HTML attributes for the menu container tag.
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.

public string|null $lastItemCssClass = null

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

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.

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().
public array|null $params = null

The parameters used to determine if a menu item is active or not.

If not set, it will use $_GET.

public string|null $route = null

The route used to determine if a menu item is active or not.

If not set, it will use the route of the current request.

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.

public function run(): mixed

Renders the menu.

Returns

mixed

protected function isItemActive(array $item): bool

Checks 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

ParameterTypeDescription
$itemarrayThe menu item to be checked

Returns

bool: Whether the menu item is active

protected function normalizeItems(array $items, bool &$active): array

Normalizes the $items property to remove invisible items and activate certain items.

Parameters

ParameterTypeDescription
$itemsarrayThe items to be normalized.
$activeboolWhether there is an active child menu item.

Returns

array: The normalized menu items

protected function renderItem(array $item): string

Renders the content of a menu item.

Note that the container and the sub-menus are not rendered here.

Parameters

ParameterTypeDescription
$itemarrayThe menu item to be rendered. Please refer to $items to see what data might be in the item.

Returns

string: The rendering result

protected function renderItems(array $items): string

Recursively renders the menu items (without the container tag).

Parameters

ParameterTypeDescription
$itemsarrayThe menu items to be rendered recursively

Returns

string: The rendering result