Nav.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\bootstrap;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\ArrayHelper;
  11. /**
  12. * Nav renders a nav HTML component.
  13. *
  14. * For example:
  15. *
  16. * ```php
  17. * echo Nav::widget([
  18. * 'items' => [
  19. * [
  20. * 'label' => 'Home',
  21. * 'url' => ['site/index'],
  22. * 'linkOptions' => [...],
  23. * ],
  24. * [
  25. * 'label' => 'Dropdown',
  26. * 'items' => [
  27. * ['label' => 'Level 1 - Dropdown A', 'url' => '#'],
  28. * '<li class="divider"></li>',
  29. * '<li class="dropdown-header">Dropdown Header</li>',
  30. * ['label' => 'Level 1 - Dropdown B', 'url' => '#'],
  31. * ],
  32. * ],
  33. * [
  34. * 'label' => 'Login',
  35. * 'url' => ['site/login'],
  36. * 'visible' => Yii::$app->user->isGuest
  37. * ],
  38. * ],
  39. * 'options' => ['class' =>'nav-pills'], // set this to nav-tab to get tab-styled navigation
  40. * ]);
  41. * ```
  42. *
  43. * Note: Multilevel dropdowns beyond Level 1 are not supported in Bootstrap 3.
  44. *
  45. * @see http://getbootstrap.com/components/#dropdowns
  46. * @see http://getbootstrap.com/components/#nav
  47. *
  48. * @author Antonio Ramirez <amigo.cobos@gmail.com>
  49. * @since 2.0
  50. */
  51. class Nav extends Widget
  52. {
  53. /**
  54. * @var array list of items in the nav widget. Each array element represents a single
  55. * menu item which can be either a string or an array with the following structure:
  56. *
  57. * - label: string, required, the nav item label.
  58. * - url: optional, the item's URL. Defaults to "#".
  59. * - visible: bool, optional, whether this menu item is visible. Defaults to true.
  60. * - linkOptions: array, optional, the HTML attributes of the item's link.
  61. * - options: array, optional, the HTML attributes of the item container (LI).
  62. * - active: bool, optional, whether the item should be on active state or not.
  63. * - dropDownOptions: array, optional, the HTML options that will passed to the [[Dropdown]] widget.
  64. * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget,
  65. * or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus.
  66. * - encode: bool, optional, whether the label will be HTML-encoded. If set, supersedes the $encodeLabels option for only this item.
  67. *
  68. * If a menu item is a string, it will be rendered directly without HTML encoding.
  69. */
  70. public $items = [];
  71. /**
  72. * @var bool whether the nav items labels should be HTML-encoded.
  73. */
  74. public $encodeLabels = true;
  75. /**
  76. * @var bool whether to automatically activate items according to whether their route setting
  77. * matches the currently requested route.
  78. * @see isItemActive
  79. */
  80. public $activateItems = true;
  81. /**
  82. * @var bool whether to activate parent menu items when one of the corresponding child menu items is active.
  83. */
  84. public $activateParents = false;
  85. /**
  86. * @var string the route used to determine if a menu item is active or not.
  87. * If not set, it will use the route of the current request.
  88. * @see params
  89. * @see isItemActive
  90. */
  91. public $route;
  92. /**
  93. * @var array the parameters used to determine if a menu item is active or not.
  94. * If not set, it will use `$_GET`.
  95. * @see route
  96. * @see isItemActive
  97. */
  98. public $params;
  99. /**
  100. * @var string this property allows you to customize the HTML which is used to generate the drop down caret symbol,
  101. * which is displayed next to the button text to indicate the drop down functionality.
  102. * Defaults to `null` which means `<span class="caret"></span>` will be used. To disable the caret, set this property to be an empty string.
  103. */
  104. public $dropDownCaret;
  105. /**
  106. * @var string name of a class to use for rendering dropdowns within this widget. Defaults to [[Dropdown]].
  107. * @since 2.0.7
  108. */
  109. public $dropdownClass = 'yii\bootstrap\Dropdown';
  110. /**
  111. * Initializes the widget.
  112. */
  113. public function init()
  114. {
  115. parent::init();
  116. if ($this->route === null && Yii::$app->controller !== null) {
  117. $this->route = Yii::$app->controller->getRoute();
  118. }
  119. if ($this->params === null) {
  120. $this->params = Yii::$app->request->getQueryParams();
  121. }
  122. if ($this->dropDownCaret === null) {
  123. $this->dropDownCaret = '<span class="caret"></span>';
  124. }
  125. Html::addCssClass($this->options, ['widget' => 'nav']);
  126. }
  127. /**
  128. * Renders the widget.
  129. */
  130. public function run()
  131. {
  132. BootstrapAsset::register($this->getView());
  133. return $this->renderItems();
  134. }
  135. /**
  136. * Renders widget items.
  137. */
  138. public function renderItems()
  139. {
  140. $items = [];
  141. foreach ($this->items as $i => $item) {
  142. if (isset($item['visible']) && !$item['visible']) {
  143. continue;
  144. }
  145. $items[] = $this->renderItem($item);
  146. }
  147. return Html::tag('ul', implode("\n", $items), $this->options);
  148. }
  149. /**
  150. * Renders a widget's item.
  151. * @param string|array $item the item to render.
  152. * @return string the rendering result.
  153. * @throws InvalidConfigException
  154. */
  155. public function renderItem($item)
  156. {
  157. if (is_string($item)) {
  158. return $item;
  159. }
  160. if (!isset($item['label'])) {
  161. throw new InvalidConfigException("The 'label' option is required.");
  162. }
  163. $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
  164. $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
  165. $options = ArrayHelper::getValue($item, 'options', []);
  166. $items = ArrayHelper::getValue($item, 'items');
  167. $url = ArrayHelper::getValue($item, 'url', '#');
  168. $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);
  169. if (isset($item['active'])) {
  170. $active = ArrayHelper::remove($item, 'active', false);
  171. } else {
  172. $active = $this->isItemActive($item);
  173. }
  174. if (empty($items)) {
  175. $items = '';
  176. } else {
  177. $linkOptions['data-toggle'] = 'dropdown';
  178. Html::addCssClass($options, ['widget' => 'dropdown']);
  179. Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
  180. if ($this->dropDownCaret !== '') {
  181. $label .= ' ' . $this->dropDownCaret;
  182. }
  183. if (is_array($items)) {
  184. $items = $this->isChildActive($items, $active);
  185. $items = $this->renderDropdown($items, $item);
  186. }
  187. }
  188. if ($active) {
  189. Html::addCssClass($options, 'active');
  190. }
  191. return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
  192. }
  193. /**
  194. * Renders the given items as a dropdown.
  195. * This method is called to create sub-menus.
  196. * @param array $items the given items. Please refer to [[Dropdown::items]] for the array structure.
  197. * @param array $parentItem the parent item information. Please refer to [[items]] for the structure of this array.
  198. * @return string the rendering result.
  199. * @since 2.0.1
  200. */
  201. protected function renderDropdown($items, $parentItem)
  202. {
  203. /** @var Widget $dropdownClass */
  204. $dropdownClass = $this->dropdownClass;
  205. return $dropdownClass::widget([
  206. 'options' => ArrayHelper::getValue($parentItem, 'dropDownOptions', []),
  207. 'items' => $items,
  208. 'encodeLabels' => $this->encodeLabels,
  209. 'clientOptions' => false,
  210. 'view' => $this->getView(),
  211. ]);
  212. }
  213. /**
  214. * Check to see if a child item is active optionally activating the parent.
  215. * @param array $items @see items
  216. * @param bool $active should the parent be active too
  217. * @return array @see items
  218. */
  219. protected function isChildActive($items, &$active)
  220. {
  221. foreach ($items as $i => $child) {
  222. if (is_array($child) && !ArrayHelper::getValue($child, 'visible', true)) {
  223. continue;
  224. }
  225. if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
  226. Html::addCssClass($items[$i]['options'], 'active');
  227. if ($this->activateParents) {
  228. $active = true;
  229. }
  230. }
  231. $childItems = ArrayHelper::getValue($child, 'items');
  232. if (is_array($childItems)) {
  233. $activeParent = false;
  234. $items[$i]['items'] = $this->isChildActive($childItems, $activeParent);
  235. if ($activeParent) {
  236. Html::addCssClass($items[$i]['options'], 'active');
  237. $active = true;
  238. }
  239. }
  240. }
  241. return $items;
  242. }
  243. /**
  244. * Checks whether a menu item is active.
  245. * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
  246. * When the `url` option of a menu item is specified in terms of an array, its first element is treated
  247. * as the route for the item and the rest of the elements are the associated parameters.
  248. * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
  249. * be considered active.
  250. * @param array $item the menu item to be checked
  251. * @return bool whether the menu item is active
  252. */
  253. protected function isItemActive($item)
  254. {
  255. if (!$this->activateItems) {
  256. return false;
  257. }
  258. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  259. $route = $item['url'][0];
  260. if ($route[0] !== '/' && Yii::$app->controller) {
  261. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  262. }
  263. if (ltrim($route, '/') !== $this->route) {
  264. return false;
  265. }
  266. unset($item['url']['#']);
  267. if (count($item['url']) > 1) {
  268. $params = $item['url'];
  269. unset($params[0]);
  270. foreach ($params as $name => $value) {
  271. if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
  272. return false;
  273. }
  274. }
  275. }
  276. return true;
  277. }
  278. return false;
  279. }
  280. }