自定义简单的PHP模版引擎
定义文件:
1.创建目录文件tpl
2.创建模版处理文件tpl/Template.php
3.显示处理页面 tpl/index.php
4.创建模版文件 tpl/index.html
5.编译目录文件 tpl/compile
tpl/Template.php源代码
<?phpclassTemplate{//模版中的变量protected$tplVals=array();//编译文件路径protected$compileFile='./compile/';//编译文件扩展名private$compileExtendName='.php';//模版文件扩展名private$tplExtendName='.html';publicfunction__construct(){}/***替换模版文件中的变量*@paramarray$data模版文件的内容*@returnstring$data替换模版文件的内容*/privatefunctionreplaceTplVar($data){foreach($this->tplValsas$k=>$v){$data=str_replace('{$'.$k.'}',$v,$data);}return$data;}/***显示模版*@paramunkown$tpl*/publicfunctiondisplay($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;}/***模版变量绑定*@paramstring$name模版变量名*@paramstring$value模版变量值*@returnnull*/publicfunctionassign($name,$value){$this->tplVals[$name]=$value;}}
tpl/index.php源代码
<?phprequire_once'./template.php';$tpl=newTemplate();$tpl->assign('title','自定义smart有模版引擎');$tpl->assign('content','这是模本内容');$tpl->display('index');
tpl/index.html源代码
<!doctypehtml><html><head><title>欢迎大家来零壹码学习自定义模版引擎</title><metacharset="utf-8"/></head><body><h2>{$title}</h2><p>{$content}</p></body></html>
执行index.php文件之后结果:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。