页面“模板”布局。 HTML header.php vs page.php

时间:2012-05-06 17:15:06

标签: php html html5

之前我曾问过类似的问题,但我对这种创建页面的“风格”有一个更具体的问题。
我有3页的模板,header.php,page.php和footer.php。我试图允许自己在一个页面内轻松编辑网站的某些部分,但也可以在每页上添加额外的内容。我目前的结构是:
的header.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Website Name<? if ($title) echo ' &ndash; ' . $title; ?></title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

page.php文件

<?
$title = 'Page Title';
require_once('includes/header.php');
?>
<!-- Any extra stuff for the header goes here -->
</head>
<body>
Page content goes here.
<? require_once('includes/footer.php'); ?>

footer.php

<footer>
I am a footer
</footer>
</body>
</html>

虽然这样做有效,但由于我的header.php页面不包含<body>中的任何内容,因此我无法轻松制作可公开编辑的标题(菜单等)。但是,关闭header.php中的<head>将不允许我每页添加额外的文件(例如特定于页面的javascript)。据我所知,<body>标签中包含的CSS和javascript不是一个好主意 我猜是在<head>标签之后,需要在每个页面的顶部添加一个文件(例如,menu.php)?然而,这看起来不那么容易阅读/自然,我觉得必须有更好的解决方案吗?

3 个答案:

答案 0 :(得分:2)

一个简单的解决方案是在内部“header.php”中添加一行来回显$ extraHeaders的内容:

<!DOCTYPE html>
<html>
<head>
<?php echo $extraHeaders ?>
...

然后,您要将特定标题添加到(样式表,javascript文件等)的任何页面,只需将其包含在$ extraHeaders变量中:

$extraHeaders = '<script type="text/javascript" src="myscripts.js"></script>'

它将自动包含在该页面的标题中。


要解决语法高亮问题并避免必须转义引号,可以使用输出缓冲区语法:

ob_start();
?>
<your html goes here> Alternatively, you can include an html file here.
<?php
$extraHeaders = ob_get_contents();
ob_end_clean(); 
...

这将允许您使用变量,如前所述,但使用语法突出显示,并且不需要转义任何内容。

答案 1 :(得分:0)

您可以使用ob_start +正则表达式({title}{scripts}等标记在加载“页面”结束时访问。

答案 2 :(得分:0)

制作一个_autoload()脚本来预加载所有这些php文件。

这样,当有任何新东西要放时,你总是可以使用包含_autoload()函数的脚本并在那里更新它。

顺便说一下,将javascript放在<body>标记的最后是一个很好的做法。

相关问题