自定义简单的PHP模版引擎

定义文件:

    1. 创建目录文件tpl

    2. 创建模版处理文件tpl/Template.php

    3. 显示处理页面 tpl/index.php

    4. 创建模版文件 tpl/index.html

    5. 编译目录文件 tpl/compile

 自定义模版引擎目录结构

tpl/Template.php源代码

<?php
class Template {

	// 模版中的变量
	protected $tplVals = array();

	// 编译文件路径
	protected $compileFile = './compile/';

	// 编译文件扩展名
	private $compileExtendName = '.php';

	// 模版文件扩展名
	private $tplExtendName = '.html';

	public function __construct(){}

	/**
	 * 替换模版文件中的变量
	 * @param  array $data 模版文件的内容
	 * @return  string $data 替换模版文件的内容
	 */
	private function replaceTplVar($data){
		foreach($this->tplVals as $k=>$v) {
			$data = str_replace('{$'.$k.'}', $v, $data);
		}
		return $data;
	}

	/**
	 * 显示模版
	 * @param  unkown $tpl
	 */
	public function display($tpl) {
		// 获取模版内容
		$content = file_get_contents($tpl.$this->tplExtendName);
		
		// 替换模版中的变量
		$content = $this->replaceTplVar($content);


		// 编译后的文件
		$compileFile = $this->compileFile.md5($tpl).$this->compileExtendName;
		
		// 给编译后的文件添加内容
		file_put_contents($compileFile, $content);
		
		// 引入编译文件
		require_once $compileFile;
		
	}


	/**
	 * 模版变量绑定
	 * @param  string $name  模版变量名
	 * @param  string $value 模版变量值
	 * @return null
	 */
	public function assign($name, $value) {
		$this->tplVals[$name] = $value;
	}
}

  

tpl/index.php源代码

<?php
require_once './template.php';

$tpl = new Template();
$tpl->assign('title','自定义smart有模版引擎');
$tpl->assign('content','这是模本内容');
$tpl->display('index');

 

 tpl/index.html源代码

<!doctype html>
<html>
<head>
<title>欢迎大家来零壹码学习自定义模版引擎</title>
<meta charset="utf-8" />	
</head>
<body>
	<h1>{$title}</h1>
	<p>{$content}</p>
</body>
</html>

  

执行index.php文件之后结果:

转载于:https://www.cnblogs.com/lingyima/p/7654416.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值