smarty自定义模板

来源:互联网 发布:现在开淘宝店卖什么好 编辑:程序博客网 时间:2024/05/17 21:57
根据课上理解:在*.php文件中写出自己所需要的模板,再由模板类的文件找到所对应的模板文件*.html,然后返回到*.php中,由*.php文件来显示。

  如:*.php文件    (本文件使用模板类)          

               <?php
                             
                 include("MyTpl.php");  -----------  包含该模板文件
                 $tpl = new MyTpl();--------创建模板对象

                $title="smarty学习";
                $content="smarty模板的介绍";(定义的两个变量)

                $tpl->assign("title",$title);
                $tpl->assign("content",$content);(分配变量)

               其中:$tpl是生成的对象

                          assign(模板的东西)是这个对象的方法

                          title是模板中访问的变量名

                          $title是变量的值-------------------------------------------就这样把值$title传到模板中了!!!

 

               $tpl->display("a.html");----------调用模板文件

                ?>

         *.html       (模板文件)

           <html>
               <head><title><{  $title  }></title></head>
          <body>
               <p><{ $content }></p>
         </body>
         </html>

 MyTpl.php(模板类文件)

<?php
class MyTpl{
 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();
     }


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

}

//$content---整个模板文件
//功能:从指定的模板文件中获取所有的<{$titlename}>结构,全部替换成<?php echo $titlename;?
function tpl_replace($content){
  
 
//定义模板文件中<{ $title }>结构的正则表达式
 $pattern = '/\<\{\s*\$([a-zA-Z_\x7f\xff][0-9a-zA-Z_\x7f\xff]*)\s*\}\>/i';
 //替换后为:<?php echo $title;?>格式
 //本文件中保存变量采取的是$this->tpl_vars[title]=$value;
    $replacement='<?php echo $this->tpl_vars["${1}"];?>';
 
 //替换后反悔一个新的html文件
     $repcontent = preg_replace($pattern,$replacement,$content);
     return $repcontent;
}

//将tpl_replace方法里返回的新文件保存到template下
//$fileName---*.html或者*.tpl
function display($fileName){
    $tplFile=$this->template_dir.$fileName;  
    $repcontent = $this->tpl_replace(file_get_contents($tplFile));

   //file_get_contents函数把整个文件读入一个字符串中。
   
   //将该编译后的文件存储到templates_c里 com_***.php
     $comFileName = $this->compile_dir."com_".basename($tplFile).".php";
 
  //将变量$repcontent写入到com_a.php文件
   $handle=fopen($comFileName,"w+");
   fwrite($handle,$repcontent);
   fclose($handle);
   include($comFileName);
     }
}


?>

原创粉丝点击