CMenu.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * CMenu class file.
  4. *
  5. * @author Jonah Turnquist <poppitypop@gmail.com>
  6. * @author Qiang Xue <qiang.xue@gmail.com>
  7. * @link http://www.yiiframework.com/
  8. * @copyright 2008-2013 Yii Software LLC
  9. * @license http://www.yiiframework.com/license/
  10. */
  11. /**
  12. * CMenu displays a multi-level menu using nested HTML lists.
  13. *
  14. * The main property of CMenu is {@link items}, which specifies the possible items in the menu.
  15. * A menu item has three main properties: visible, active and items. The "visible" property
  16. * specifies whether the menu item is currently visible. The "active" property specifies whether
  17. * the menu item is currently selected. And the "items" property specifies the child menu items.
  18. *
  19. * The following example shows how to use CMenu:
  20. * <pre>
  21. * $this->widget('zii.widgets.CMenu', array(
  22. * 'items'=>array(
  23. * // Important: you need to specify url as 'controller/action',
  24. * // not just as 'controller' even if default acion is used.
  25. * array('label'=>'Home', 'url'=>array('site/index')),
  26. * // 'Products' menu item will be selected no matter which tag parameter value is since it's not specified.
  27. * array('label'=>'Products', 'url'=>array('product/index'), 'items'=>array(
  28. * array('label'=>'New Arrivals', 'url'=>array('product/new', 'tag'=>'new')),
  29. * array('label'=>'Most Popular', 'url'=>array('product/index', 'tag'=>'popular')),
  30. * )),
  31. * array('label'=>'Login', 'url'=>array('site/login'), 'visible'=>Yii::app()->user->isGuest),
  32. * ),
  33. * ));
  34. * </pre>
  35. *
  36. *
  37. * @author Jonah Turnquist <poppitypop@gmail.com>
  38. * @author Qiang Xue <qiang.xue@gmail.com>
  39. * @package zii.widgets
  40. * @since 1.1
  41. */
  42. class CMenu extends CWidget
  43. {
  44. /**
  45. * @var array list of menu items. Each menu item is specified as an array of name-value pairs.
  46. * Possible option names include the following:
  47. * <ul>
  48. * <li>label: string, optional, specifies the menu item label. When {@link encodeLabel} is true, the label
  49. * will be HTML-encoded. If the label is not specified, it defaults to an empty string.</li>
  50. * <li>url: string or array, optional, specifies the URL of the menu item. It is passed to {@link CHtml::normalizeUrl}
  51. * to generate a valid URL. If this is not set, the menu item will be rendered as a span text.</li>
  52. * <li>visible: boolean, optional, whether this menu item is visible. Defaults to true.
  53. * This can be used to control the visibility of menu items based on user permissions.</li>
  54. * <li>items: array, optional, specifies the sub-menu items. Its format is the same as the parent items.</li>
  55. * <li>active: boolean, optional, whether this menu item is in active state (currently selected).
  56. * If a menu item is active and {@link activeClass} is not empty, its CSS class will be appended with {@link activeClass}.
  57. * If this option is not set, the menu item will be set active automatically when the current request
  58. * is triggered by {@link url}. Note that the GET parameters not specified in the 'url' option will be ignored.</li>
  59. * <li>template: string, optional, the template used to render this menu item.
  60. * When this option is set, it will override the global setting {@link itemTemplate}.
  61. * Please see {@link itemTemplate} for more details. This option has been available since version 1.1.1.</li>
  62. * <li>linkOptions: array, optional, additional HTML attributes to be rendered for the link or span tag of the menu item.</li>
  63. * <li>itemOptions: array, optional, additional HTML attributes to be rendered for the container tag of the menu item.</li>
  64. * <li>submenuOptions: array, optional, additional HTML attributes to be rendered for the container of the submenu if this menu item has one.
  65. * When this option is set, the {@link submenuHtmlOptions} property will be ignored for this particular submenu.
  66. * This option has been available since version 1.1.6.</li>
  67. * </ul>
  68. */
  69. public $items=array();
  70. /**
  71. * @var string the template used to render an individual menu item. In this template,
  72. * the token "{menu}" will be replaced with the corresponding menu link or text.
  73. * If this property is not set, each menu will be rendered without any decoration.
  74. * This property will be overridden by the 'template' option set in individual menu items via {@items}.
  75. * @since 1.1.1
  76. */
  77. public $itemTemplate;
  78. /**
  79. * @var boolean whether the labels for menu items should be HTML-encoded. Defaults to true.
  80. */
  81. public $encodeLabel=true;
  82. /**
  83. * @var string the CSS class to be appended to the active menu item. Defaults to 'active'.
  84. * If empty, the CSS class of menu items will not be changed.
  85. */
  86. public $activeCssClass='active';
  87. /**
  88. * @var boolean whether to automatically activate items according to whether their route setting
  89. * matches the currently requested route. Defaults to true.
  90. * @since 1.1.3
  91. */
  92. public $activateItems=true;
  93. /**
  94. * @var boolean whether to activate parent menu items when one of the corresponding child menu items is active.
  95. * The activated parent menu items will also have its CSS classes appended with {@link activeCssClass}.
  96. * Defaults to false.
  97. */
  98. public $activateParents=false;
  99. /**
  100. * @var boolean whether to hide empty menu items. An empty menu item is one whose 'url' option is not
  101. * set and which doesn't contain visible child menu items. Defaults to true.
  102. */
  103. public $hideEmptyItems=true;
  104. /**
  105. * @var array HTML attributes for the menu's root container tag
  106. */
  107. public $htmlOptions=array();
  108. /**
  109. * @var array HTML attributes for the submenu's container tag.
  110. */
  111. public $submenuHtmlOptions=array();
  112. /**
  113. * @var string the HTML element name that will be used to wrap the label of all menu links.
  114. * For example, if this property is set as 'span', a menu item may be rendered as
  115. * &lt;li&gt;&lt;a href="url"&gt;&lt;span&gt;label&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
  116. * This is useful when implementing menu items using the sliding window technique.
  117. * Defaults to null, meaning no wrapper tag will be generated.
  118. * @since 1.1.4
  119. */
  120. public $linkLabelWrapper;
  121. /**
  122. * @var array HTML attributes for the links' wrap element specified in
  123. * {@link linkLabelWrapper}.
  124. * @since 1.1.13
  125. */
  126. public $linkLabelWrapperHtmlOptions=array();
  127. /**
  128. * @var string the CSS class that will be assigned to the first item in the main menu or each submenu.
  129. * Defaults to null, meaning no such CSS class will be assigned.
  130. * @since 1.1.4
  131. */
  132. public $firstItemCssClass;
  133. /**
  134. * @var string the CSS class that will be assigned to the last item in the main menu or each submenu.
  135. * Defaults to null, meaning no such CSS class will be assigned.
  136. * @since 1.1.4
  137. */
  138. public $lastItemCssClass;
  139. /**
  140. * @var string the CSS class that will be assigned to every item.
  141. * Defaults to null, meaning no such CSS class will be assigned.
  142. * @since 1.1.9
  143. */
  144. public $itemCssClass;
  145. /**
  146. * Initializes the menu widget.
  147. * This method mainly normalizes the {@link items} property.
  148. * If this method is overridden, make sure the parent implementation is invoked.
  149. */
  150. public function init()
  151. {
  152. if(isset($this->htmlOptions['id']))
  153. $this->id=$this->htmlOptions['id'];
  154. else
  155. $this->htmlOptions['id']=$this->id;
  156. $route=$this->getController()->getRoute();
  157. $this->items=$this->normalizeItems($this->items,$route,$hasActiveChild);
  158. }
  159. /**
  160. * Calls {@link renderMenu} to render the menu.
  161. */
  162. public function run()
  163. {
  164. $this->renderMenu($this->items);
  165. }
  166. /**
  167. * Renders the menu items.
  168. * @param array $items menu items. Each menu item will be an array with at least two elements: 'label' and 'active'.
  169. * It may have three other optional elements: 'items', 'linkOptions' and 'itemOptions'.
  170. */
  171. protected function renderMenu($items)
  172. {
  173. if(count($items))
  174. {
  175. echo CHtml::openTag('ul',$this->htmlOptions)."\n";
  176. $this->renderMenuRecursive($items);
  177. echo CHtml::closeTag('ul');
  178. }
  179. }
  180. /**
  181. * Recursively renders the menu items.
  182. * @param array $items the menu items to be rendered recursively
  183. */
  184. protected function renderMenuRecursive($items)
  185. {
  186. $count=0;
  187. $n=count($items);
  188. foreach($items as $item)
  189. {
  190. $count++;
  191. $options=isset($item['itemOptions']) ? $item['itemOptions'] : array();
  192. $class=array();
  193. if($item['active'] && $this->activeCssClass!='')
  194. $class[]=$this->activeCssClass;
  195. if($count===1 && $this->firstItemCssClass!==null)
  196. $class[]=$this->firstItemCssClass;
  197. if($count===$n && $this->lastItemCssClass!==null)
  198. $class[]=$this->lastItemCssClass;
  199. if($this->itemCssClass!==null)
  200. $class[]=$this->itemCssClass;
  201. if($class!==array())
  202. {
  203. if(empty($options['class']))
  204. $options['class']=implode(' ',$class);
  205. else
  206. $options['class'].=' '.implode(' ',$class);
  207. }
  208. echo CHtml::openTag('li', $options);
  209. $menu=$this->renderMenuItem($item);
  210. if(isset($this->itemTemplate) || isset($item['template']))
  211. {
  212. $template=isset($item['template']) ? $item['template'] : $this->itemTemplate;
  213. echo strtr($template,array('{menu}'=>$menu));
  214. }
  215. else
  216. echo $menu;
  217. if(isset($item['items']) && count($item['items']))
  218. {
  219. echo "\n".CHtml::openTag('ul',isset($item['submenuOptions']) ? $item['submenuOptions'] : $this->submenuHtmlOptions)."\n";
  220. $this->renderMenuRecursive($item['items']);
  221. echo CHtml::closeTag('ul')."\n";
  222. }
  223. echo CHtml::closeTag('li')."\n";
  224. }
  225. }
  226. /**
  227. * Renders the content of a menu item.
  228. * Note that the container and the sub-menus are not rendered here.
  229. * @param array $item the menu item to be rendered. Please see {@link items} on what data might be in the item.
  230. * @return string
  231. * @since 1.1.6
  232. */
  233. protected function renderMenuItem($item)
  234. {
  235. if(isset($item['url']))
  236. {
  237. $label=$this->linkLabelWrapper===null ? $item['label'] : CHtml::tag($this->linkLabelWrapper, $this->linkLabelWrapperHtmlOptions, $item['label']);
  238. return CHtml::link($label,$item['url'],isset($item['linkOptions']) ? $item['linkOptions'] : array());
  239. }
  240. else
  241. return CHtml::tag('span',isset($item['linkOptions']) ? $item['linkOptions'] : array(), $item['label']);
  242. }
  243. /**
  244. * Normalizes the {@link items} property so that the 'active' state is properly identified for every menu item.
  245. * @param array $items the items to be normalized.
  246. * @param string $route the route of the current request.
  247. * @param boolean $active whether there is an active child menu item.
  248. * @return array the normalized menu items
  249. */
  250. protected function normalizeItems($items,$route,&$active)
  251. {
  252. foreach($items as $i=>$item)
  253. {
  254. if(isset($item['visible']) && !$item['visible'])
  255. {
  256. unset($items[$i]);
  257. continue;
  258. }
  259. if(!isset($item['label']))
  260. $item['label']='';
  261. if($this->encodeLabel)
  262. $items[$i]['label']=CHtml::encode($item['label']);
  263. $hasActiveChild=false;
  264. if(isset($item['items']))
  265. {
  266. $items[$i]['items']=$this->normalizeItems($item['items'],$route,$hasActiveChild);
  267. if(empty($items[$i]['items']) && $this->hideEmptyItems)
  268. {
  269. unset($items[$i]['items']);
  270. if(!isset($item['url']))
  271. {
  272. unset($items[$i]);
  273. continue;
  274. }
  275. }
  276. }
  277. if(!isset($item['active']))
  278. {
  279. if($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item,$route))
  280. $active=$items[$i]['active']=true;
  281. else
  282. $items[$i]['active']=false;
  283. }
  284. elseif($item['active'])
  285. $active=true;
  286. }
  287. return array_values($items);
  288. }
  289. /**
  290. * Checks whether a menu item is active.
  291. * This is done by checking if the currently requested URL is generated by the 'url' option
  292. * of the menu item. Note that the GET parameters not specified in the 'url' option will be ignored.
  293. * @param array $item the menu item to be checked
  294. * @param string $route the route of the current request
  295. * @return boolean whether the menu item is active
  296. */
  297. protected function isItemActive($item,$route)
  298. {
  299. if(isset($item['url']) && is_array($item['url']) && !strcasecmp(trim($item['url'][0],'/'),$route))
  300. {
  301. unset($item['url']['#']);
  302. if(count($item['url'])>1)
  303. {
  304. foreach(array_splice($item['url'],1) as $name=>$value)
  305. {
  306. if(!isset($_GET[$name]) || $_GET[$name]!=$value)
  307. return false;
  308. }
  309. }
  310. return true;
  311. }
  312. return false;
  313. }
  314. }