CMenu.php 12 KB

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