我看到这种方法存在一些严重的维护问题。
每次添加新页面时,都必须添加三个(目前)if 语句。
upper.php对其他页面了解太多——它们的窗口标题和元数据。
我建议不要使用变量在upper.php$urhere
中做出所有决定,而是设置变量,例如窗口标题和元数据,这些变量可以直接由upper.php使用。这是一个例子:
上层.php
<meta name="description" content="<?php echo $description ?>"/>
...
<title><?php echo $title ?></title>
...
<?php
$pageTypeToLinkMap = array(
'home' => array(
'url' => '/home',
'linkText' => 'Home'
),
'about' => array(
'url' => '/about',
'linkText' => 'About',
'sublinks' => array(
'who-we-are' => array(
'url' => '/who-we-are',
'linkText' => 'Who We Are'
),
'what-we-do' => array(
'url' => '/what-we-do',
'linkText' => 'What We Do',
'sublinks' => array(
'business' => array(
'url' => '/business',
'linkText' => 'Business'
),
'technology' => array(
'url' => '/technology',
'linkText' => 'Technology'
)
)
)
)
),
'contact' => array(
'url' => '/contact',
'linkText' => 'Contact'
)
);
function getLinkElement($pageType, array $linkData)
{
$class = $urhere == $pageType ? 'urhere' : '';
$anchorElement = "<a href=\"$linkData[url]\" class=\"$class\">$linkData[linkText]</a>";
if (isset($linkData['sublinks']))
{
$sublinkElements = array();
foreach ($linkData['sublinks'] as $sublinkPageType => $sublinkData)
$sublinkElements[] = getLinkElement($sublinkPageType, $sublinkData);
$sublinksListElement = '<ul>' . implode($sublinkElements) . '</ul>';
}
else
$sublinksListElement = '';
return "<li>$anchorElement$sublinksListElement</li>";
}
?>
<div id="nav">
<ul>
<?php foreach ($pageTypeToLinkMap as $pageType => $link) echo getLinkElement($pageType, array $link); ?>
</ul>
</div>
索引.php
<?php
$pageTitle = "Home";
$description = "This is home.";
$urhere = "home"; // I guess you still need this variable to make decisions in the "nav" div.
?>
<div>This is the Home page content</div>
关于.php
<?php
$pageTitle = "About";
$description = "About us";
$urhere = "about";
?>
<div>This is the About page content</div>
编辑
作为对您的评论的回应,以下是在保持相同原始结构的同时改进您的upper.php的方法:
上层.php
<?php
$titles = array(
'home' => 'Home page Title',
'about' => 'About page Title',
'contact' => 'Contact page Title'
);
$descriptions = array(
'home' => 'Home page description',
'about' => 'About page description',
'contact' => 'Contact page description'
);
$linkClasses = array_fill_keys(array_keys($titles), '');
$linkClasses[$urhere] = 'urhere';
?>
...
<meta name="description" content="<?php echo $descriptions[$urhere] ?>"/>
...
<title><?php echo $titles[$urhere] ?></title>
...
<div id="nav">
<ul>
<li><a href="/home" class="<?php echo $linkClasses['home'] ?>">Home</a></li>
<li><a href="/about" class="<?php echo $linkClasses['about'] ?>">About</a></li>
<li><a href="/contact" class="<?php echo $linkClasses['contact'] ?>">Contact</a></li>
</ul>
</div>
你去吧,if-less 代码。