PHP 编程/模板
外观
	
	
< PHP 编程
PHP 中模板的最简单用法对于减少错误和页面开发时间非常有效。首先,确保您的服务器启用了 PHP 等等。
准备开始后,创建一个作为所有页面模板的页面。例如
This is a title at the top of my page This is the body of my page This is a copyright notice
现在,假设您想要创建另外两个具有相同页眉和页脚的页面。您无需再次编写代码。您可以将页眉保存为一个模板,将页脚保存为另一个模板。只需获取页眉中的所有 HTML 代码,直到正文文本开始的部分
<html><body><p>This is a title at the top of my page</p>
现在将此代码保存为单独的文件。我喜欢使用 .inc 扩展名(页脚也一样)
<p>This is the bottom of my page</p></body></html>
现在,在您的主页面中,只需键入
 <?php require('header.inc'); ?>
 <p>this is the body of my page</p>
 <?php require('footer.inc'); ?>
这就是您的页面。将其保存为 .php 文件,上传并查看。
您也可以使用 include() 或 include_once() 函数,即使文件无法包含,页面也应继续加载。
require()、include() 和 include_once() 函数将与其他文件类型一起使用,并且可以在页面的任何位置使用。
高级:尝试使用 if 语句将它们与动态模板结合起来... 哦...
托管模板允许您使用模板引擎创建和使用 PHP 模板。PHP 开发人员/设计师无需创建引擎即可使用它。最可靠的 PHP 模板引擎是 Smarty([1])。托管模板系统易于使用,并且主要用于大型网站,因为需要动态分页。MediaWiki 是托管模板系统的例子之一。托管模板对于新手和高级用户都很容易使用,例如
- index.php
 // This script is based on Smarty
 require_once("libs/Smarty.inc.php");
 // Compiled File Directory
 $smarty->compile_dir = "compiled";
 // Template Directory
 $smarty->template_dir = "templates";
 // Assign a Variable
 $smarty->assign("variable","value");
 // Display The Parsed Template
 $smarty->display("template.tpl");
- template.tpl
The Value of Variable is : {$variable}
- 输出
The Value of Variable is : value
模板引擎非常有用,但是如果您只是在寻找基本的搜索和替换模板功能,编写您自己的脚本轻而易举。
- 简单的模板函数
function Template($file, $array) {
	if (file_exists($file)) {
		$output = file_get_contents($file);
		foreach ($array as $key => $val) {
			$replace = '{'.$key.'}';
			$output = str_replace($replace, $val, $output);
		}
		return $output;
	}
}
- 使用函数
$fruit = 'Watermelon';
$color = 'Gray';
//parse and return template
$Template_Tpl = Template('template.tpl',
	array
	(
		'fruit'	=> $fruit,
		'color'	=> $color
	));
//display template
echo $Template_Tpl;
- template.tpl,用于上述函数的模板
<p>
  <b>Your Favorite Food Is: {fruit}</b>
  <b>Your Favorite Color Is: {color}</b>
</p>
- 解析后的模板输出
<p>
  <b>Your Favorite Food Is: Watermelon</b>
  <b>Your Favorite Color Is: Gray</b>
</p>

