Nav.php 6.31 KB
Newer Older
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\bootstrap;

10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\ArrayHelper;
13 14 15 16 17 18 19 20 21 22 23 24
use yii\helpers\Html;

/**
 * Nav renders a nav HTML component.
 *
 * For example:
 *
 * ```php
 * echo Nav::widget(array(
 *     'items' => array(
 *         array(
 *             'label' => 'Home',
25
 *             'url' => array('site/index'),
26
 *             'linkOptions' => array(...),
27 28 29
 *         ),
 *         array(
 *             'label' => 'Dropdown',
Mojtaba Salehi committed
30
 *             'items' => array(
31
 *                  array(
Mojtaba Salehi committed
32
 *                      'label' => 'Level 1 -DropdownA',
33
 *                      'url' => '#',
Mojtaba Salehi committed
34 35 36 37 38 39
 *                      'items' => array(
 *                          array(
 *                              'label' => 'Level 2 -DropdownA',
 *                              'url' => '#',
 *                          ),
 *                      ),
40 41
 *                  ),
 *                  array(
Mojtaba Salehi committed
42
 *                      'label' => 'Level 1 -DropdownB',
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
 *                      'url' => '#',
 *                  ),
 *             ),
 *         ),
 *     ),
 * ));
 * ```
 *
 * @see http://twitter.github.io/bootstrap/components.html#nav
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @since 2.0
 */
class Nav extends Widget
{
	/**
	 * @var array list of items in the nav widget. Each array element represents a single
Qiang Xue committed
59
	 * menu item which can be either a string or an array with the following structure:
60
	 *
61 62
	 * - label: string, required, the nav item label.
	 * - url: optional, the item's URL. Defaults to "#".
63
	 * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
64 65 66
	 * - linkOptions: array, optional, the HTML attributes of the item's link.
	 * - options: array, optional, the HTML attributes of the item container (LI).
	 * - active: boolean, optional, whether the item should be on active state or not.
67
	 * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
Qiang Xue committed
68
	 *   or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
Qiang Xue committed
69
	 *
Alexander Makarov committed
70
	 * If a menu item is a string, it will be rendered directly without HTML encoding.
71 72
	 */
	public $items = array();
73 74 75 76
	/**
	 * @var boolean whether the nav items labels should be HTML-encoded.
	 */
	public $encodeLabels = true;
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
	/**
	 * @var boolean whether to automatically activate items according to whether their route setting
	 * matches the currently requested route.
	 * @see isItemActive
	 */
	public $activateItems = true;
	/**
	 * @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
	 */
	public $route;
	/**
	 * @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
	 */
	public $params;
97 98 99 100 101 102 103


	/**
	 * Initializes the widget.
	 */
	public function init()
	{
104
		parent::init();
105 106 107 108 109 110
		if ($this->route === null && Yii::$app->controller !== null) {
			$this->route = Yii::$app->controller->getRoute();
		}
		if ($this->params === null) {
			$this->params = $_GET;
		}
111
		Html::addCssClass($this->options, 'nav');
112 113 114 115 116 117 118 119
	}

	/**
	 * Renders the widget.
	 */
	public function run()
	{
		echo $this->renderItems();
120
		BootstrapAsset::register($this->getView());
121 122 123 124 125 126 127 128
	}

	/**
	 * Renders widget items.
	 */
	public function renderItems()
	{
		$items = array();
129 130 131 132 133
		foreach ($this->items as $i => $item) {
			if (isset($item['visible']) && !$item['visible']) {
				unset($items[$i]);
				continue;
			}
134 135 136 137 138 139 140 141
			$items[] = $this->renderItem($item);
		}

		return Html::tag('ul', implode("\n", $items), $this->options);
	}

	/**
	 * Renders a widget's item.
142
	 * @param string|array $item the item to render.
143 144 145 146 147 148 149 150 151 152 153
	 * @return string the rendering result.
	 * @throws InvalidConfigException
	 */
	public function renderItem($item)
	{
		if (is_string($item)) {
			return $item;
		}
		if (!isset($item['label'])) {
			throw new InvalidConfigException("The 'label' option is required.");
		}
154
		$label = $this->encodeLabels ? Html::encode($item['label']) : $item['label'];
155
		$options = ArrayHelper::getValue($item, 'options', array());
Mojtaba Salehi committed
156
		$items = ArrayHelper::getValue($item, 'items');
157 158 159
		$url = Html::url(ArrayHelper::getValue($item, 'url', '#'));
		$linkOptions = ArrayHelper::getValue($item, 'linkOptions', array());

160 161 162 163 164 165 166
		if (isset($item['active'])) {
			$active = ArrayHelper::remove($item, 'active', false);
		} else {
			$active = $this->isItemActive($item);
		}

		if ($active) {
167
			Html::addCssClass($options, 'active');
168
		}
169

Mojtaba Salehi committed
170
		if ($items !== null) {
171
			$linkOptions['data-toggle'] = 'dropdown';
172 173
			Html::addCssClass($options, 'dropdown');
			Html::addCssClass($urlOptions, 'dropdown-toggle');
174
			$label .= ' ' . Html::tag('b', '', array('class' => 'caret'));
Mojtaba Salehi committed
175 176 177
			if (is_array($items)) {
				$items = Dropdown::widget(array(
					'items' => $items,
178
					'encodeLabels' => $this->encodeLabels,
Qiang Xue committed
179 180
					'clientOptions' => false,
				));
Qiang Xue committed
181
			}
182 183
		}

Mojtaba Salehi committed
184
		return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
185
	}
186 187 188 189 190 191 192 193 194 195 196 197 198 199


	/**
	 * 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.
	 * @param array $item the menu item to be checked
	 * @return boolean whether the menu item is active
	 */
	protected function isItemActive($item)
	{
200 201 202 203 204 205 206 207
		if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
			$route = $item['url'][0];
			if ($route[0] !== '/' && Yii::$app->controller) {
				$route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
			}
			if (ltrim($route, '/') !== $this->route) {
				return false;
			}
208 209 210 211 212 213 214 215 216 217 218 219
			unset($item['url']['#']);
			if (count($item['url']) > 1) {
				foreach (array_splice($item['url'], 1) as $name => $value) {
					if (!isset($this->params[$name]) || $this->params[$name] != $value) {
						return false;
					}
				}
			}
			return true;
		}
		return false;
	}
Qiang Xue committed
220
}