原文出处:Just for fun——PHP框架之简单的模板引擎 感谢原作者的分享
原理
使用模板引擎的好处是数据和视图分离。一个简单的PHP模板引擎原理是
- extract数组($data),使key对应的变量可以在此作用域起效
- 打开输出控制缓冲(ob_start)
- include模板文件,include遇到html的内容会输出,但是因为打开了缓冲,内容输出到了缓冲中
- ob_get_contents()读取缓冲中内容,然后关闭缓冲ob_end_clean()
实现
封装一个Template类
<?php class Template { private $templatePath; private $data; public function setTemplatePath($path) { $this->templatePath = $path; } /** * 设置模板变量 * @param $key string | array * @param $value */ public function assign($key, $value) { if(is_array($key)) { $this->data = array_merge($this->data, $key); } elseif(is_string($key)) { $this->data[$key] = $value; } } /** * 渲染模板 * @param $template * @return string */ public function display($template) { extract($this->data); ob_start(); include ($this->templatePath . $template); $res = ob_get_contents(); ob_end_clean(); return $res; } }
测试
test.php
<?php
include_once './template.php';
$template = new Template();
$template->setTemplatePath(__DIR__ . '/template/');
$template->assign('name', 'salamander');
$res = $template->display('index.html');
echo $res;
template目录下index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板测试</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
h1 {
text-align: center;
padding-top: 20px;
}
</style>
</head>
<body>
<h1><?=$name?></h1>
</body>
</html>
效果预览:
Tip
为什么display要返回一个字符串呢?原因是为了更好的控制,嵌入到控制器类中。
对于循环语句怎么办呢?这个的话,请看流程控制的替代语法

