Menu.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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\widgets;
  8. use Yii;
  9. use yii\base\Widget;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Html;
  12. /**
  13. * Menu displays a multi-level menu using nested HTML lists.
  14. *
  15. * The main property of Menu is [[items]], which specifies the possible items in the menu.
  16. * A menu item can contain sub-items which specify the sub-menu under that menu item.
  17. *
  18. * Menu checks the current route and request parameters to toggle certain menu items
  19. * with active state.
  20. *
  21. * Note that Menu only renders the HTML tags about the menu. It does do any styling.
  22. * You are responsible to provide CSS styles to make it look like a real menu.
  23. *
  24. * The following example shows how to use Menu:
  25. *
  26. * ~~~
  27. * echo Menu::widget([
  28. * 'items' => [
  29. * // Important: you need to specify url as 'controller/action',
  30. * // not just as 'controller' even if default action is used.
  31. * ['label' => 'Home', 'url' => ['site/index']],
  32. * // 'Products' menu item will be selected as long as the route is 'product/index'
  33. * ['label' => 'Products', 'url' => ['product/index'], 'items' => [
  34. * ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']],
  35. * ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']],
  36. * ]],
  37. * ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
  38. * ],
  39. * ]);
  40. * ~~~
  41. *
  42. * @author Qiang Xue <[email protected]>
  43. * @since 2.0
  44. */
  45. class Menu extends Widget
  46. {
  47. /**
  48. * @var array list of menu items. Each menu item should be an array of the following structure:
  49. *
  50. * - label: string, optional, specifies the menu item label. When [[encodeLabels]] is true, the label
  51. * will be HTML-encoded. If the label is not specified, an empty string will be used.
  52. * - url: string or array, optional, specifies the URL of the menu item. It will be processed by [[Html::url]].
  53. * When this is set, the actual menu item content will be generated using [[linkTemplate]];
  54. * otherwise, [[labelTemplate]] will be used.
  55. * - visible: boolean, optional, whether this menu item is visible. Defaults to true.
  56. * - items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.
  57. * - active: boolean, optional, whether this menu item is in active state (currently selected).
  58. * If a menu item is active, its CSS class will be appended with [[activeCssClass]].
  59. * If this option is not set, the menu item will be set active automatically when the current request
  60. * is triggered by [[url]]. For more details, please refer to [[isItemActive()]].
  61. * - template: string, optional, the template used to render the content of this menu item.
  62. * The token `{url}` will be replaced by the URL associated with this menu item,
  63. * and the token `{label}` will be replaced by the label of the menu item.
  64. * If this option is not set, [[linkTemplate]] or [[labelTemplate]] will be used instead.
  65. * - options: array, optional, the HTML attributes for the menu container tag.
  66. */
  67. public $items = [];
  68. /**
  69. * @var array list of HTML attributes for the menu container tag. This will be overwritten
  70. * by the "options" set in individual [[items]]. The following special options are recognized:
  71. *
  72. * - tag: string, defaults to "li", the tag name of the item container tags.
  73. */
  74. public $itemOptions = [];
  75. /**
  76. * @var string the template used to render the body of a menu which is a link.
  77. * In this template, the token `{url}` will be replaced with the corresponding link URL;
  78. * while `{label}` will be replaced with the link text.
  79. * This property will be overridden by the `template` option set in individual menu items via [[items]].
  80. */
  81. public $linkTemplate = '<a href="{url}">{label}</a>';
  82. /**
  83. * @var string the template used to render the body of a menu which is NOT a link.
  84. * In this template, the token `{label}` will be replaced with the label of the menu item.
  85. * This property will be overridden by the `template` option set in individual menu items via [[items]].
  86. */
  87. public $labelTemplate = '{label}';
  88. /**
  89. * @var string the template used to render a list of sub-menus.
  90. * In this template, the token `{items}` will be replaced with the renderer sub-menu items.
  91. */
  92. public $submenuTemplate = "\n<ul>\n{items}\n</ul>\n";
  93. /**
  94. * @var boolean whether the labels for menu items should be HTML-encoded.
  95. */
  96. public $encodeLabels = true;
  97. /**
  98. * @var string the CSS class to be appended to the active menu item.
  99. */
  100. public $activeCssClass = 'active';
  101. /**
  102. * @var boolean whether to automatically activate items according to whether their route setting
  103. * matches the currently requested route.
  104. * @see isItemActive()
  105. */
  106. public $activateItems = true;
  107. /**
  108. * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
  109. * The activated parent menu items will also have its CSS classes appended with [[activeCssClass]].
  110. */
  111. public $activateParents = false;
  112. /**
  113. * @var boolean whether to hide empty menu items. An empty menu item is one whose `url` option is not
  114. * set and which has no visible child menu items.
  115. */
  116. public $hideEmptyItems = true;
  117. /**
  118. * @var array the HTML attributes for the menu's container tag. The following special options are recognized:
  119. *
  120. * - tag: string, defaults to "ul", the tag name of the item container tags.
  121. */
  122. public $options = [];
  123. /**
  124. * @var string the CSS class that will be assigned to the first item in the main menu or each submenu.
  125. * Defaults to null, meaning no such CSS class will be assigned.
  126. */
  127. public $firstItemCssClass;
  128. /**
  129. * @var string the CSS class that will be assigned to the last item in the main menu or each submenu.
  130. * Defaults to null, meaning no such CSS class will be assigned.
  131. */
  132. public $lastItemCssClass;
  133. /**
  134. * @var string the route used to determine if a menu item is active or not.
  135. * If not set, it will use the route of the current request.
  136. * @see params
  137. * @see isItemActive()
  138. */
  139. public $route;
  140. /**
  141. * @var array the parameters used to determine if a menu item is active or not.
  142. * If not set, it will use `$_GET`.
  143. * @see route
  144. * @see isItemActive()
  145. */
  146. public $params;
  147. /**
  148. * Renders the menu.
  149. */
  150. public function run()
  151. {
  152. if ($this->route === null && Yii::$app->controller !== null) {
  153. $this->route = Yii::$app->controller->getRoute();
  154. }
  155. if ($this->params === null) {
  156. $this->params = $_GET;
  157. }
  158. $items = $this->normalizeItems($this->items, $hasActiveChild);
  159. $options = $this->options;
  160. $tag = ArrayHelper::remove($options, 'tag', 'ul');
  161. echo Html::tag($tag, $this->renderItems($items), $options);
  162. }
  163. /**
  164. * Recursively renders the menu items (without the container tag).
  165. * @param array $items the menu items to be rendered recursively
  166. * @return string the rendering result
  167. */
  168. protected function renderItems($items)
  169. {
  170. $n = count($items);
  171. $lines = [];
  172. foreach ($items as $i => $item) {
  173. $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
  174. $tag = ArrayHelper::remove($options, 'tag', 'li');
  175. $class = [];
  176. if ($item['active']) {
  177. $class[] = $this->activeCssClass;
  178. }
  179. if ($i === 0 && $this->firstItemCssClass !== null) {
  180. $class[] = $this->firstItemCssClass;
  181. }
  182. if ($i === $n - 1 && $this->lastItemCssClass !== null) {
  183. $class[] = $this->lastItemCssClass;
  184. }
  185. if (!empty($class)) {
  186. if (empty($options['class'])) {
  187. $options['class'] = implode(' ', $class);
  188. } else {
  189. $options['class'] .= ' ' . implode(' ', $class);
  190. }
  191. }
  192. $menu = $this->renderItem($item);
  193. if (!empty($item['items'])) {
  194. $menu .= strtr($this->submenuTemplate, [
  195. '{items}' => $this->renderItems($item['items']),
  196. ]);
  197. }
  198. $lines[] = Html::tag($tag, $menu, $options);
  199. }
  200. return implode("\n", $lines);
  201. }
  202. /**
  203. * Renders the content of a menu item.
  204. * Note that the container and the sub-menus are not rendered here.
  205. * @param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
  206. * @return string the rendering result
  207. */
  208. protected function renderItem($item)
  209. {
  210. if (isset($item['url'])) {
  211. $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate);
  212. return strtr($template, [
  213. '{url}' => Html::url($item['url']),
  214. '{label}' => $item['label'],
  215. ]);
  216. } else {
  217. $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
  218. return strtr($template, [
  219. '{label}' => $item['label'],
  220. ]);
  221. }
  222. }
  223. /**
  224. * Normalizes the [[items]] property to remove invisible items and activate certain items.
  225. * @param array $items the items to be normalized.
  226. * @param boolean $active whether there is an active child menu item.
  227. * @return array the normalized menu items
  228. */
  229. protected function normalizeItems($items, &$active)
  230. {
  231. foreach ($items as $i => $item) {
  232. if (isset($item['visible']) && !$item['visible']) {
  233. unset($items[$i]);
  234. continue;
  235. }
  236. if (!isset($item['label'])) {
  237. $item['label'] = '';
  238. }
  239. if ($this->encodeLabels) {
  240. $items[$i]['label'] = Html::encode($item['label']);
  241. }
  242. $hasActiveChild = false;
  243. if (isset($item['items'])) {
  244. $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
  245. if (empty($items[$i]['items']) && $this->hideEmptyItems) {
  246. unset($items[$i]['items']);
  247. if (!isset($item['url'])) {
  248. unset($items[$i]);
  249. continue;
  250. }
  251. }
  252. }
  253. if (!isset($item['active'])) {
  254. if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
  255. $active = $items[$i]['active'] = true;
  256. } else {
  257. $items[$i]['active'] = false;
  258. }
  259. } elseif ($item['active']) {
  260. $active = true;
  261. }
  262. }
  263. return array_values($items);
  264. }
  265. /**
  266. * Checks whether a menu item is active.
  267. * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
  268. * When the `url` option of a menu item is specified in terms of an array, its first element is treated
  269. * as the route for the item and the rest of the elements are the associated parameters.
  270. * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
  271. * be considered active.
  272. * @param array $item the menu item to be checked
  273. * @return boolean whether the menu item is active
  274. */
  275. protected function isItemActive($item)
  276. {
  277. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  278. $route = $item['url'][0];
  279. if ($route[0] !== '/' && Yii::$app->controller) {
  280. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  281. }
  282. if (ltrim($route, '/') !== $this->route) {
  283. return false;
  284. }
  285. unset($item['url']['#']);
  286. if (count($item['url']) > 1) {
  287. foreach (array_splice($item['url'], 1) as $name => $value) {
  288. if (!isset($this->params[$name]) || $this->params[$name] != $value) {
  289. return false;
  290. }
  291. }
  292. }
  293. return true;
  294. }
  295. return false;
  296. }
  297. }