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

来源:互联网 发布:mac不能玩qq游戏 编辑:程序博客网 时间:2024/05/16 07:27

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

<?phprequire './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变量赋值两次


0 0
原创粉丝点击