截至目前,我使用的方式包括为其他页面添加页眉,页脚和一些内容。
这导致更多包含然后我真的想要,因为我需要为包含添加更多内容。
例如:
<!DOCTYPE html>
<?php include('header.php'); ?>
<body>
<?php include('body-top.php');
custom html
</?php include('footer.php');
</body>
如果我可以在包含和我希望包含显示的页面上添加变量,那将是很好的。
我根本不擅长PHP,所以有没有更好的方法来使用包含?
答案 0 :(得分:1)
听起来像是Smarty
的工作看起来像这样
<?php
require 'Smarty/libs/Smarty.class.php';
$smarty = new Smarty;
$smarty->assign('title','Hello World');
$smarty->assign('hello','Hello World, this is my first Smarty!');
$smarty->display('test.tpl');
?>
test.tpl
<html>
<head>
<title>{$title}</title>
</head>
<body>
{$hello}
</body>
</html>
甚至更好的方法,使用一些PHP MVC框架,这将为您提供更多东西(不仅仅是模板系统)
答案 1 :(得分:1)
您的包含已经非常少,无需优化它们。
也不要注意那些暗示Smarty或MVC的人,因为这会大大增加包含的数量(当然,换取其他好处) -
答案 2 :(得分:1)
这很容易做到:
<强>的index.php 强>
$title = 'Hello World!';
include 'content.php';
<强> content.php 强>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body></body>
</html>
这种方法存在的问题是,你很快就会遇到问题跟踪到底发生了什么,所以使用其他答案中建议的功能可能是一个好主意。但是,对于小型项目来说,恕我直言就足够了。
答案 3 :(得分:0)
您可以将包含的文件转换为函数。 PHP有一个巧妙的技巧,即花括号(即{
和}
)之间的任何内容只有在到达代码部分时才会执行。这包括PHP标记之外的HTML代码。
这可能是我们的'header.php'文件,我们将当前代码包装在一个函数中。
<?php function doHeader($title) { ?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<?php } ?>
然后我们为它做一个测试。无论我们的测试人员/来电者选择通过哪个$title
都显示在我们的输出中。
<?php
// All included here
include_once('header.php');
?><!DOCTYPE html>
<?php doHeader('My page title'); ?>
<body></body>
</html>
这会产生输出
<!DOCTYPE html>
<html>
<head>
<title>My page title</title>
</head>
<body></body>
</html>