You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 line
9.7KB

  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: boolean, 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: boolean, 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: boolean, 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 boolean whether the nav items labels should be HTML-encoded.
  73. */
  74. public $encodeLabels = true;
  75. /**
  76. * @var boolean 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 boolean 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 `<b class="caret"></b>` will be used. To disable the caret, set this property to be an empty string.
  103. */
  104. public $dropDownCaret;
  105. /**
  106. * Initializes the widget.
  107. */
  108. public function init()
  109. {
  110. parent::init();
  111. if ($this->route === null && Yii::$app->controller !== null) {
  112. $this->route = Yii::$app->controller->getRoute();
  113. }
  114. if ($this->params === null) {
  115. $this->params = Yii::$app->request->getQueryParams();
  116. }
  117. if ($this->dropDownCaret === null) {
  118. $this->dropDownCaret = Html::tag('b', '', ['class' => 'caret']);
  119. }
  120. Html::addCssClass($this->options, ['widget' => 'nav']);
  121. }
  122. /**
  123. * Renders the widget.
  124. */
  125. public function run()
  126. {
  127. BootstrapAsset::register($this->getView());
  128. return $this->renderItems();
  129. }
  130. /**
  131. * Renders widget items.
  132. */
  133. public function renderItems()
  134. {
  135. $items = [];
  136. foreach ($this->items as $i => $item) {
  137. if (isset($item['visible']) && !$item['visible']) {
  138. continue;
  139. }
  140. $items[] = $this->renderItem($item);
  141. }
  142. return Html::tag('ul', implode("\n", $items), $this->options);
  143. }
  144. /**
  145. * Renders a widget's item.
  146. * @param string|array $item the item to render.
  147. * @return string the rendering result.
  148. * @throws InvalidConfigException
  149. */
  150. public function renderItem($item)
  151. {
  152. if (is_string($item)) {
  153. return $item;
  154. }
  155. if (!isset($item['label'])) {
  156. throw new InvalidConfigException("The 'label' option is required.");
  157. }
  158. $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
  159. $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
  160. $options = ArrayHelper::getValue($item, 'options', []);
  161. $items = ArrayHelper::getValue($item, 'items');
  162. $url = ArrayHelper::getValue($item, 'url', '#');
  163. $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);
  164. if (isset($item['active'])) {
  165. $active = ArrayHelper::remove($item, 'active', false);
  166. } else {
  167. $active = $this->isItemActive($item);
  168. }
  169. if (empty($items)) {
  170. $items = '';
  171. } else {
  172. $linkOptions['data-toggle'] = 'dropdown';
  173. Html::addCssClass($options, ['widget' => 'dropdown']);
  174. Html::addCssClass($linkOptions, ['widget' => 'dropdown-toggle']);
  175. if ($this->dropDownCaret !== '') {
  176. $label .= ' ' . $this->dropDownCaret;
  177. }
  178. if (is_array($items)) {
  179. if ($this->activateItems) {
  180. $items = $this->isChildActive($items, $active);
  181. }
  182. $items = $this->renderDropdown($items, $item);
  183. }
  184. }
  185. if ($this->activateItems && $active) {
  186. Html::addCssClass($options, 'active');
  187. }
  188. return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
  189. }
  190. /**
  191. * Renders the given items as a dropdown.
  192. * This method is called to create sub-menus.
  193. * @param array $items the given items. Please refer to [[Dropdown::items]] for the array structure.
  194. * @param array $parentItem the parent item information. Please refer to [[items]] for the structure of this array.
  195. * @return string the rendering result.
  196. * @since 2.0.1
  197. */
  198. protected function renderDropdown($items, $parentItem)
  199. {
  200. return Dropdown::widget([
  201. 'options' => ArrayHelper::getValue($parentItem, 'dropDownOptions', []),
  202. 'items' => $items,
  203. 'encodeLabels' => $this->encodeLabels,
  204. 'clientOptions' => false,
  205. 'view' => $this->getView(),
  206. ]);
  207. }
  208. /**
  209. * Check to see if a child item is active optionally activating the parent.
  210. * @param array $items @see items
  211. * @param boolean $active should the parent be active too
  212. * @return array @see items
  213. */
  214. protected function isChildActive($items, &$active)
  215. {
  216. foreach ($items as $i => $child) {
  217. if (ArrayHelper::remove($items[$i], 'active', false) || $this->isItemActive($child)) {
  218. Html::addCssClass($items[$i]['options'], 'active');
  219. if ($this->activateParents) {
  220. $active = true;
  221. }
  222. }
  223. }
  224. return $items;
  225. }
  226. /**
  227. * Checks whether a menu item is active.
  228. * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
  229. * When the `url` option of a menu item is specified in terms of an array, its first element is treated
  230. * as the route for the item and the rest of the elements are the associated parameters.
  231. * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
  232. * be considered active.
  233. * @param array $item the menu item to be checked
  234. * @return boolean whether the menu item is active
  235. */
  236. protected function isItemActive($item)
  237. {
  238. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  239. $route = $item['url'][0];
  240. if ($route[0] !== '/' && Yii::$app->controller) {
  241. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  242. }
  243. if (ltrim($route, '/') !== $this->route) {
  244. return false;
  245. }
  246. unset($item['url']['#']);
  247. if (count($item['url']) > 1) {
  248. $params = $item['url'];
  249. unset($params[0]);
  250. foreach ($params as $name => $value) {
  251. if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
  252. return false;
  253. }
  254. }
  255. }
  256. return true;
  257. }
  258. return false;
  259. }
  260. }