我正在尝试通过包含文件来整理每个页面的代码来清理我的php网页中的代码:
文件:head.php
<!DOCTYPE html>
<html>
<head>
<title> *Dynamic Page Title* </title>
<meta name"description" "Dynamic Description">
<link href="#">
</head>
文件:footer.php
<footer>
<ul>
<a href="#"><li>Home</li></a>
<a href="#"><li>Page 1</li></a>
<a href="#"><li>Page 2</li></a>
</ul>
</footer>
<script src="#">
</body>
</html>
文件:navbar.php
<header class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<a href="#" class="navbar-brand"></a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><i class="fa fa-bars"></i></button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="index">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">FAQ</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</div>
</header>
文件:index.php
<?php include('head.php'); ?>
<?php include('nav-bar.php'); ?>
<body>
Index Page, Home has an active class
<?php include('footer.php'); ?>
文件:Page-1.php
<?php include('head.php'); ?>
<?php include('nav-bar.php'); ?>
<body>
Index Page, Page 1 in nav-bar has an active class
<?php include('footer.php'); ?>
你们得到了主要的想法。我想了解如何在导航栏中的不同页面中添加活动类,以及如何为每个页面添加不同的标题和元标记。
任何帮助?
答案 0 :(得分:3)
您可以在文件中定义变量:
index.php
:
<?php $title = 'Home'; ?>
<?php $metaTags = 'tag1 tag2'; ?>
<?php $currentPage = 'index'; ?>
<?php include('head.php'); ?>
<?php include('nav-bar.php'); ?>
<body>
Index Page, Home has an active class
<?php include('footer.php'); ?>
然后在包含的文件中使用这些变量:
head.php
:
<!DOCTYPE html>
<html>
<head>
<title><?php echo($title); ?></title>
<meta name"description" "<?php echo($metaTags); ?>"><!-- note that this code is wrong -->
<link href="#">
</head>
navbar.php
:
<header class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<a href="#" class="navbar-brand"></a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><i class="fa fa-bars"></i></button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li <?php if ($currentPage === 'Home') {echo 'class="active"';} ?>><a href="index">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">FAQ</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
</div>
</header>
在最后一部分中,使用数组更容易,而不是为每一行重复相同的代码:
<ul class="nav navbar-nav navbar-right">
<?php
// Define each name associated with an URL
$urls = array(
'Home' => '/',
'Page 1' => '/page1',
// …
);
foreach ($urls as $name => $url) {
print '<li '.(($currentPage === $name) ? ' class="active" ': '').
'><a href="'.$url.'">'.$name.'</a></li>';
}
?>
</ul>