您应该创建一个 PHP 类并将其包含在您的标头中,或者将其设置为您的标头。在页面上调用它,然后为类变量分配值,然后您可以回显一个单独的类函数,该函数使用您需要的变量值。如果您不熟悉该过程,我可以提供一个示例。
Header.php 简单示例:
<?php
class Template
{
private $active_nav;
private __construct()
{
}
public function set_active($page = '') // set page test value
{
$this->active_nav = $page;
}
public function get_active() // return page test value
{
return $this->active_nav;
}
public function nav_links() // this could be changed to return an entire header or part or whatever -- change the scope accordingly
{
// active link CSS is linSktyleOne
$current_page = $this->get_active();
$nav_links = '<ul>';
$nav_links .= '<li><a href="index.php" class="' . ($current_page == 'index' ? "linkSytleOne" : "linkStyleTwo") . '">Index</a></li>';
$nav_links .= '<li><a href="contact.php" class="' . ($current_page == 'contact' ? "linkSytleOne" : "linkStyleTwo") . '">Contact</a></li>';
$nav_links .= '</ul>';
return $nav_links;
}
}
contact.php 简单示例:
<?php
require_once('includes/header.php');
$template = new Template;
$template->set_active('contact');
// put all your html or other code here
echo $template->nav_links();
?> <!-- blah blah code finished --> <?
// you can always echo a footer out here through a function in the template as well
index.php 简单示例:
<?php
require_once('includes/header.php');
$template = new Template;
$template->set_active('index');
// put all your html or other code here
echo $template->nav_links();
?> <!-- blah blah code finished --> <?
// you can always echo a footer out here through a function in the template as well
所有这些帮助更有意义吗?您只需向每个页面添加 1 行代码,如果您真的想要花哨,您可以通过使用$_SERVER['REQUEST_URI']
值的子字符串进行条件测试来删除每个页面上的 set 函数调用,并将条件设置在类的构造函数。