我是一名PHP初学者。我在许多教程中看到他们建议用include替换页面的头部。但每个页面的标题和描述应该不同。所以,我不明白。有办法解决这个问题吗?或者如果想要拥有独特的标题和描述,我不应该包括头部?什么是最佳做法?
(我理解一个包含的实用性:如果我必须做出改变,我只需要去一个地方。)
网页示例:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title of the page</title>
<meta name="description" content="Description of the page">
<link rel="stylesheet" href="externs/stylesheet/general.css" >
</head>
<body>
<div>Content</div>
</body>
</html>
将头部放入另一个包含
的页面的页面include "head.php";
<div>Content</div>
include "footer.php";
答案 0 :(得分:0)
您的包含文件不必是静态的。您可以创建head.php
和footer.php
并在其中使用一些PHP代码。例如:
<?php
// head.php
$title = getPageTitle(); // you need to implement a way of getting a title here
?>
<!-- html code skipped -->
<title><?= $title ?></title>
您可以在footer.php
中执行类似操作。这里的挑战是定义一个数据源,您可以从中获取这些文件中的动态信息,并且不会破坏主代码中的任何内容。
include "head.php"; // here head.php is dynamic by itself
<div>Content</div>
include "footer.php"; // and footer.php also knows what to do
答案 1 :(得分:0)
Yuri建议使用header.php和footer.php肯定会提供一个更易于管理的网站,可以在许多不同的PHP文件中复制相同的样式和结构HTML。但是根据我在其他地方的评论,在生成格式良好的HTML时很难实现这些。此外,您的代码应该分成可管理的单元 - 因此创建和消费&#39; $ title&#39;可能会在您的代码中处于非常不同的位置(范围)。
当然,您应该尝试最小化在包含文件的_main上下文中运行的代码量 - 它应该只在显式调用时执行。使用单个文件简化了维护 - 例如
<?php
include('project/templater.inc.php');
$t=new template();
t->pre_output();
print "<html>\n";
$t->head("My test page");
$t->page_start();
// all entry point scripts contain something like the above, and a page_end()
// next, all the page specific stuff....
?>
<div>Hello world</div>
<?php
$t->page_end();
print "</html>";
$t->clean_up();
许多Web框架通过使用前端控制器模式解决了这个问题 - 所有请求都被发送到特定的脚本,该脚本处理页面的所有常见元素(CSS / Javascript依赖项,包括路径,常见HTML片段,如导航,验证)认证)。
我个人更喜欢使用依赖注入 - 其中有一个包含文件,提供可调用的函数/方法来生成这些片段,然后从URL直接寻址的脚本中调用它们:
<?php
include("project/stdpage.inc.php");
render_page('content_for_this_page');
function content_for_this_page()
{
print "<div>Hello world</div>\n";
}
这里,包含一个文件只不过是定义函数,包括&#34; render_page()&#34;当调用它时,在某些时候,它知道它需要包含一些特定于页面的内容 - 这是由参数中的回调定义的。