php简单的自定义模板引擎类。

本文介绍了一个简单的PHP模板引擎实现,该引擎能够解析特定语法的模板文件,并将变量替换为实际值,支持基本的模板缓存机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
	class MyTpl {
		private $template_dir;
		private $compile_dir;
		private $tpl_vars=array();

		public function __construct($template_dir="./templates", $compile_dir="./templates_c"){
			$this->template_dir=rtrim($template_dir,"/").'/';
			$this->compile_dir=rtrim($compile_dir, "/").'/';
		}

		public function assign($tpl_var, $value=null){
			if($tpl_var!="")
				$this->tpl_vars[$tpl_var]=$value;
		}

		public function display($fileName){
			$tplFile=$this->template_dir.$fileName;

			if(!file_exists($tplFile)){
				return false;
			}

			$comFileName=$this->compile_dir."com_".$fileName.".php";

			if(!file_exists($comFileName) || filemtime($comFileName) < filemtime($tplFile)){
				$repContent=$this->tpl_replace(file_get_contents($tplFile));

				file_put_contents($comFileName, $repContent);	
			}

			include $comFileName;
			
		}

		private function tpl_replace($content){
				$pattern=array(
						'/\<\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i'
					);

				$replacement=array(
					'<?php echo $this->tpl_vars["${1}"]; ?>'
					);
			
				$repContent=preg_replace($pattern, $replacement, $content);

				return $repContent;
		}

	}
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值