写模板--Smarty类的编译功能仿写

本文介绍了一个简单的PHP模板引擎实现——Smarty。通过Smarty可以实现PHP与HTML的分离,提高开发效率。文章详细解释了Smarty的工作原理,包括如何编译模板、传递变量及显示编译后的页面。

smarty模板

功能:php和html分离=>controller和view

eg:

<p>{$str}</p>  =>  <p><?php echo $str; ?></p> 

把模板经过编译/解析(compile)变为后者



mini.class.php

<?php
/*smarty模板*/
class mini{
	// compile编译;template模板;编译是从高语言,编到低语言

	//模板和编译后的文件 地址
	public $template_dir='';
	public $compile_dir='';	
	//接收外面变量
	public $arr;

	//编译方法过程:读取模板内容-》编译-》保存
	/*
	parm $template 模板文件名
	return 编译文件地址*/
	public function compile($template){
		$temp=$this->template_dir.'/'.$template;
		$comp=$this->compile_dir.'/'.$template.'.php';

		/*若模板没改动就用之前编译过的html;模板时间且小于编译时间*/
		if (file_exists($comp)&& filemtime($temp)<filemtime($comp)) {
			return $comp;
		}

		//读取模板的内容
		$res=file_get_contents($temp);
		//编译...{-->>>{$...$str-->>>$this->arr['str']  (str是例子)
		$res=str_replace('{$','<?php echo $this->arr[\'',$res);
		//error替换反了错,高到低,所以用<?php替换 {}
		$res=str_replace('}','\'] ;?>', $res);

		//保存,comp是编译文件的路径
		file_put_contents($comp,$res);
		return $comp;	
	}

	public function display($template){
		$path= $this->compile($template);
		include($path);
	}

	public function assign($k,$v){
		$this->arr[$k]=$v;
		return $this->arr;
	}
}


?>


调用 php

<?php
require './mini.class.php';

//变量
$str='hello,this is my best day~';
//调用模板转换
$mini=new mini();

//error Undefined variable: template_dir  写错成$mini->$template_dir
$mini->template_dir='./template';
$mini->compile_dir='./compile';


/*引入编译后的文件地址
$path=$mini->compile('temp.html');
include($path);
希望能自动引入*/

//$mini->display('temp.html');但这样不能引入,因为变量是全局,而display用不了外面的。所以变量需要放到类属性里
$mini->assign('str',$str);
$mini->display('temp.html');


?>


smarty是一个类,要使用必先引入类并实例化;assign赋值;display编译自动include


smarty之不好

1写模板浪费时间

2变量赋值两次


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值