php 框架 模板_Just for fun——PHP框架之简单的模板引擎

原理

使用模板引擎的好处是数据和视图分离。一个简单的PHP模板引擎原理是

extract数组($data),使key对应的变量可以在此作用域起效

打开输出控制缓冲(ob_start)

include模板文件,include遇到html的内容会输出,但是因为打开了缓冲,内容输出到了缓冲中

ob_get_contents()读取缓冲中内容,然后关闭缓冲ob_end_clean()

实现

封装一个Template类

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

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文件

模板测试

* {

padding: 0;

margin: 0;

box-sizing: border-box;

}

h1 {

text-align: center;

padding-top: 20px;

}

=$name?>

5267ca5de5f7a08b7b6dfe44be548254.png

87909d4586c5037c5449130172650a9c.png

Tip

为什么display要返回一个字符串呢?原因是为了更好的控制,嵌入到控制器类中。

对于循环语句怎么办呢?这个的话,请看流程控制的替代语法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值