Menu.php 10.3 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\widgets;

10
use Yii;
Qiang Xue committed
11 12 13 14
use yii\base\Widget;
use yii\helpers\Html;

/**
15
 * Menu displays a multi-level menu using nested HTML lists.
Qiang Xue committed
16
 *
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
 * 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 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:
 * 
 * ~~~
 * $this->widget('yii\widgets\Menu', array(
 *     'items' => array(
 *         // Important: you need to specify url as 'controller/action',
 *         // not just as 'controller' even if default acion is used.
 *         array('label' => 'Home', 'url' => array('site/index')),
 *         // 'Products' menu item will be selected as long as the route is 'product/index'
 *         array('label' => 'Products', 'url' => array('product/index'), 'items' => array(
 *             array('label' => 'New Arrivals', 'url' => array('product/index', 'tag' => 'new')),
 *             array('label' => 'Most Popular', 'url' => array('product/index', 'tag' => 'popular')),
 *         )),
 *         array('label' => 'Login', 'url' => array('site/login'), 'visible' => Yii::app()->user->isGuest),
 *     ),
 * ));
 * ~~~
 * 
Qiang Xue committed
44 45 46 47 48 49
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Menu extends Widget
{
	/**
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	 * @var array 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.
	 * - url: string or array, optional, specifies the URL of the menu item. It will be processed by [[Html::url]].
	 *   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, optional, whether this menu item is in active state (currently selected).
	 *   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. 
Qiang Xue committed
67 68 69
	 */
	public $items = array();
	/**
70 71 72 73 74 75 76 77 78 79
	 * @var string 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 $linkTemplate = '<a href="{url}">{label}</a>';
	/**
	 * @var string 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]].
Qiang Xue committed
80
	 */
81
	public $labelTemplate = '{label}';
Qiang Xue committed
82
	/**
83 84
	 * @var string the template used to render a list of sub-menus.
	 * In this template, the token `{items}` will be replaced with the renderer sub-menu items.
Qiang Xue committed
85
	 */
86
	public $submenuTemplate = "\n<ul>\n{items}\n</ul>\n";
Qiang Xue committed
87
	/**
88 89 90 91 92
	 * @var boolean whether the labels for menu items should be HTML-encoded.
	 */
	public $encodeLabels = true;
	/**
	 * @var string the CSS class to be appended to the active menu item.
Qiang Xue committed
93 94 95 96
	 */
	public $activeCssClass = 'active';
	/**
	 * @var boolean whether to automatically activate items according to whether their route setting
97 98
	 * matches the currently requested route.
	 * @see isItemActive
Qiang Xue committed
99 100 101 102
	 */
	public $activateItems = true;
	/**
	 * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
103
	 * The activated parent menu items will also have its CSS classes appended with [[activeCssClass]].
Qiang Xue committed
104 105 106
	 */
	public $activateParents = false;
	/**
107 108
	 * @var boolean 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.
Qiang Xue committed
109 110 111
	 */
	public $hideEmptyItems = true;
	/**
112
	 * @var array the HTML attributes for the menu's container tag.
Qiang Xue committed
113 114 115 116 117 118 119 120 121 122 123 124 125
	 */
	public $options = array();
	/**
	 * @var string 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 $firstItemCssClass;
	/**
	 * @var string 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 $lastItemCssClass;
	/**
126 127 128 129
	 * @var string 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. 
	 * @see params
	 * @see isItemActive
Qiang Xue committed
130
	 */
131
	public $route;
Qiang Xue committed
132
	/**
133 134 135 136
	 * @var array the parameters used to determine if a menu item is active or not.
	 * If not set, it will use `$_GET`.
	 * @see route
	 * @see isItemActive
Qiang Xue committed
137
	 */
138 139
	public $params;

Qiang Xue committed
140 141

	/**
142
	 * Renders the menu.
Qiang Xue committed
143 144 145
	 */
	public function run()
	{
146 147 148 149 150
		if ($this->route === null && Yii::$app->controller !== null) {
			$this->route = Yii::$app->controller->getRoute();
		}
		if ($this->params === null) {
			$this->params = $_GET;
Qiang Xue committed
151
		}
152 153
		$items = $this->normalizeItems($this->items, $hasActiveChild);
		echo Html::tag('ul', $this->renderItems($items), $this->options);
Qiang Xue committed
154 155 156
	}

	/**
157
	 * Recursively renders the menu items (without the container tag).
Qiang Xue committed
158
	 * @param array $items the menu items to be rendered recursively
159
	 * @return string the rendering result
Qiang Xue committed
160 161 162 163
	 */
	protected function renderItems($items)
	{
		$n = count($items);
164 165
		$lines = array();
		foreach ($items as $i => $item) {
Qiang Xue committed
166 167
			$options = isset($item['itemOptions']) ? $item['itemOptions'] : array();
			$class = array();
168
			if ($item['active']) {
Qiang Xue committed
169 170
				$class[] = $this->activeCssClass;
			}
171
			if ($i === 0 && $this->firstItemCssClass !== null) {
Qiang Xue committed
172 173
				$class[] = $this->firstItemCssClass;
			}
174
			if ($i === $n - 1 && $this->lastItemCssClass !== null) {
Qiang Xue committed
175 176
				$class[] = $this->lastItemCssClass;
			}
177
			if (!empty($class)) {
Qiang Xue committed
178 179 180 181 182 183 184 185
				if (empty($options['class'])) {
					$options['class'] = implode(' ', $class);
				} else {
					$options['class'] .= ' ' . implode(' ', $class);
				}
			}

			$menu = $this->renderItem($item);
186 187 188 189
			if (!empty($item['items'])) {
				$menu .= strtr($this->submenuTemplate, array(
					'{items}' => $this->renderItems($item['items']),
				));
Qiang Xue committed
190
			}
191
			$lines[] = Html::tag('li', $menu, $options);
Qiang Xue committed
192
		}
193
		return implode("\n", $lines);
Qiang Xue committed
194 195 196 197 198
	}

	/**
	 * Renders the content of a menu item.
	 * Note that the container and the sub-menus are not rendered here.
199 200
	 * @param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
	 * @return string the rendering result
Qiang Xue committed
201 202 203 204
	 */
	protected function renderItem($item)
	{
		if (isset($item['url'])) {
205 206 207 208 209
			$template = isset($item['template']) ? $item['template'] : $this->linkTemplate;
			return strtr($template, array(
				'{url}' => Html::url($item['url']),
				'{label}' => $item['label'],
			));
Qiang Xue committed
210
		} else {
211 212 213 214
			$template = isset($item['template']) ? $item['template'] : $this->labelTemplate;
			return strtr($template, array(
				'{label}' => $item['label'],
			));
Qiang Xue committed
215 216 217 218
		}
	}

	/**
219
	 * Normalizes the [[items]] property to remove invisible items and activate certain items.
Qiang Xue committed
220 221 222 223
	 * @param array $items the items to be normalized.
	 * @param boolean $active whether there is an active child menu item.
	 * @return array the normalized menu items
	 */
224
	protected function normalizeItems($items, &$active)
Qiang Xue committed
225 226 227 228 229 230 231 232 233
	{
		foreach ($items as $i => $item) {
			if (isset($item['visible']) && !$item['visible']) {
				unset($items[$i]);
				continue;
			}
			if (!isset($item['label'])) {
				$item['label'] = '';
			}
234
			if ($this->encodeLabels) {
Qiang Xue committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248
				$items[$i]['label'] = Html::encode($item['label']);
			}
			$hasActiveChild = false;
			if (isset($item['items'])) {
				$items[$i]['items'] = $this->normalizeItems($item['items'], $route, $hasActiveChild);
				if (empty($items[$i]['items']) && $this->hideEmptyItems) {
					unset($items[$i]['items']);
					if (!isset($item['url'])) {
						unset($items[$i]);
						continue;
					}
				}
			}
			if (!isset($item['active'])) {
249
				if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
Qiang Xue committed
250 251 252 253 254 255 256 257 258 259 260 261 262
					$active = $items[$i]['active'] = true;
				} else {
					$items[$i]['active'] = false;
				}
			} elseif ($item['active']) {
				$active = true;
			}
		}
		return array_values($items);
	}

	/**
	 * Checks whether a menu item is active.
263 264 265 266 267
	 * 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.
Qiang Xue committed
268 269 270
	 * @param array $item the menu item to be checked
	 * @return boolean whether the menu item is active
	 */
271
	protected function isItemActive($item)
Qiang Xue committed
272
	{
273
		if (isset($item['url']) && is_array($item['url']) && trim($item['url'][0], '/') === $this->route) {
Qiang Xue committed
274 275 276
			unset($item['url']['#']);
			if (count($item['url']) > 1) {
				foreach (array_splice($item['url'], 1) as $name => $value) {
277
					if (!isset($this->params[$name]) || $this->params[$name] != $value) {
Qiang Xue committed
278 279 280 281 282 283 284 285 286 287
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}

}