如何正确构建导航菜单,突出显示当前页面 [英] How to properly build a navigation menu that highlights the current page
问题描述
我根据 icant.co.uk 设置了一个相当简单网站的菜单。 a>。这很简单,可能有5页。小网站主要是使用 MATE 的几个表的mysql浏览器。它是一个common.php文件,包含头&页脚HTML,以便我将代码放在下面。
I've setup a menu for a fairly simple site based on icant.co.uk. It's fairly simple with maybe 5 pages. The small site is mainly a mysql browser for a few tables using MATE. Theres a common.php file that contains the header & footer HTML so thats where I put the code below.
下面的代码突出显示菜单上的当前页面。
The code below highlights the current page on the menu. Its ugly and I'm sure there has to be a better way to do it.
任何帮助都很感激,谢谢!
Any help is appreciated, thank you!
继承我的代码
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
if ($currentFile == "orders.php"){
echo '<li id="active"><a href="orders.php" id="current">Orders</a></li>';
}
else{
echo '<li><a href="orders.php">Orders</a></li>';
}
if ($currentFile == "customers.php"){
echo '<li id="active"><a href="customers.php" id="current">Customer List</a></li>';
}
else{
echo '<li><a href="customers.php">Customer List</a></li>';
}
if ($currentFile == "order_details.php"){
echo '<li id="active"><a href="order_details.php" id="current">Order Details</a></li>';
}
else{
echo '<li><a href="order_details.php">Order Details</a></li>';
}
?>
UPDATE 对于那些好奇的,下面是工作代码!
UPDATE For those curious, below is the working code!
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "order_details.php", "title" => "Order Details"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$currentAppend = ($page['file'] == $currentFile) ? ' id="current' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '<a href="' . $page['file'] . '"' . $currentAppend . '">' . $page['title'] .'</a>'
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
?>
推荐答案
不知道这是你的意思,但这样你就会摆脱这个丑陋的if-else:
Not sure if that's what you meant, but this way you'll get rid of this ugly if-else:
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '<a href="' . $page['file'] . '">' . $page['title'] .'</a>'
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
这篇关于如何正确构建导航菜单,突出显示当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!