此处的关键是使用搜索和选择适当菜单项的逻辑来设置组件router.php文件(应在前端组件的根文件夹中找到)。我很想看到这种情况自动发生,但据我所知并非如此。
最好将此代码块用于某种类型的帮助程序功能,该功能可用于自动查找最适合内容的菜单项。
这是我在几个自定义组件中使用的代码,以获取最合适的菜单项:
// I use this first empty array to avoid having unset properties in my query
$base_array = array('Itemid'=>'', 'option'=>'', 'view'=>'', 'layout'=>'', 'id'=>'');
$app =& JFactory::getApplication();
$menu = $app->getMenu();
$active = $menu->getActive();
// hack to protect the actual current item as well as the search module or other places that use JRoute::_('index.php');
if (count($query)==2 && isset($query['option']) && isset($query['Itemid']) && $query['option'] && $query['Itemid']) {
return $segments;
}
// start with no match found
$match = false;
$match_level = 0;
$query += $base_array;
// we want to find a menu item for this if possible. If the active menu item is the current menu item then we should see if there is a better match.
if (empty($query['Itemid']) || ($query['Itemid'] == $active->id && empty($query['task']))) {
// load all menu items
$items = $menu->getMenu();
// use the current item over others if it ties for the best match
if ($active->query['option'] == $query['option']) {
$match_level = 1;
$match = $active;
if ($active->query['view'] == $query['view']) {
$match_level = 2;
if ($active->query['layout'] == $query['layout'] || ($query['layout']=='default' && !$active->query['layout'])) {
$match_level = 3;
if ($active->query['id'] == $query['id']) {
$match_level = 4;
}
}
}
}
// loop through each menu item in order
foreach ($items as $item) {
$item->query += $base_array;
// base check is that it is for this component
// then cycle through each possibility finding it's match level
if ($item->query['option'] == $query['option']) {
$item_match = 1;
if ($item->query['view'] == $query['view']) {
$item_match = 2;
if (!$query['layout'] && $item->query['layout']) {
$query['layout'] = 'default';
}
if ($item->query['layout'] == $query['layout'] || ($query['layout']=='default' && !$item->query['layout'])) {
$item_match = 3;
if ($item->query['id'] == $query['id']) {
$item_match = 4;
}
}
}
}
// if this item is a better match than our current match, set it as the best match
if ($item_match > $match_level) {
$match = $item;
$match_level = $item_match;
}
}
// if there is a match update Itemid to match that menu item
if ($match) {
$query['Itemid'] = $match->id;
$menuItem = $menu->getItem($match->id);
} else {
$menuItem = $menu->getActive();
}
}
所有这一切都是一团糟(如果有人有改进,我将很乐意!),但它可以完成工作。如果当前菜单项是最匹配的,它将始终坚持下去。
否则,它将根据组件名称->视图名称->布局名称-> id值找到最佳匹配。它匹配的越靠右,我认为匹配就越好!