第一个smarty小实例~~
今天开始学习强大的smarty模版,完成了第一个smarty实例,如下:
b.php:功能页面
<?php
//首先包含该模版文件
include("MyTpl.php");
//创建模版对象
$tpl=new MyTpl();
$title="smarty学习";
$content="smarty模版的介绍";
//分配变量
$tpl->assign("title",$title);
$tpl->assign("content",$content);
//调用模版文件
$tpl->display("a.html");
?>
a.html(b.php同级目录templates文件夹下):美工页面
<html>
<head>
<title><{ $title }></title>
</head>
<body>
<p><{ $content }></p>
</body>
</html>
MyTpl.php(b.php同级目录下):模板类
<?php
class MyTpl{
/*
声明$template_dir属性,保存模版文件所在路径
声明$compile_dir属性,保存编译后文件所在路径
*/
public function __construct($template_dir="./templates",$compile_dir="./templates_c"){
$this->template_dir=rtrim($template_dir,'/').'/';
$this->compile_dir=rtrim($compile_dir,'/').'/';
$this->tpl_vars=array();
}
/*
如何实现将php文件中声明的变量分配到html(tpl)文件
使用assign()——需要两个参数$tpl_var,$value
$tpl_var--出现在模版文件(*.html/*.tpl)中的变量的名称
$value--模版文件中对应的变量的值,来自于php文件
*/
function assign($tpl_var,$value=null){
if($tpl_var!=""){
$this->tpl_vars[$tpl_var]=$value;
}
}
/*实现模版文件的调用
*display("模版文件名")
*第一步:从模版文件中获取<{$titlename}>结构
*第二步:替换成<?php echo $titlename?>语法
//$content——整个模版文件
//功能:从指定的模版文件中获取所有的<{$titlename}>结构,全部替换成<?php echo $titlename;?>
*/
function tpl_replace($content){
/*
替换函数preg_replace();
语法:mixed preg_replace(正则表达式,替换成,被替换对象)
*/
//定义模版文件中<{$title}>结构的正则表达式
$pattern = '/\<\{\s*\$([a-zA-Z_\x7f-\xff][0-9a-zA-Z_\x7f-\xff]*)\s*\}\>/i';
//替换后:<?php echo $title; ? >格式
//本文件中保存变量采取 $this->tpl_vars[$tpl_var]=$value;
$replacement='<?php echo $this->tpl_vars["${1}"];?>';
//替换后返回一个新的html文件
$repcontent=preg_replace($pattern,$replacement,$content);
return $repcontent;
}
//将tpl_replace方法里返回的新文件保存在templates_c下
//$fileName--*.html/*.tpl
function display($fileName){
//$this->template_dir="./templates";
//$fileName="a.html";
// $this->template_dir.$fileName="./templates/a.html"
$tplFile=$this->template_dir.$fileName;
//file_get_contents
$repcontent=$this->tpl_replace(file_get_contents($tplFile));
//将该编译后的文件存储到templates_c里 com_***.php
//将编译后的文件保存到templates_c
//pathname() basename() dirname()
// ./templates_c/com_a.php
$comFileName=$this->compile_dir."com_".basename($tplFile).".php";
//将变量$repcontent写入到com_a.php文件
$handle=fopen($comFileName,"w+");
fwrite($handle,$repcontent);
fclose($handle);
include($comFileName);
}
}
?>
就会在b.php同级目录下templates_c下生成com_a.html.php,其代码如下:
<html>
<head>
<title><?php echo $this->tpl_vars["title"];?></title>
</head>
<body>
<p><?php echo $this->tpl_vars["content"];?></p>
</body>
</html>
浏览器运行b.php就会出现标题为smarty学习,内容为smarty模版的介绍的效果,如下: