纵有疾风起
人生不言弃

自定义一个模板引擎

1.新建一个简单的模板demo.html

         <html>
                    <head>
                         <title>{$title}</title>
                    </head>
                    <body>
                           <h2>{ $title }</h2>
                          <div>
                             { $content }
                         </div>
                    </body>
        </html>

2.自定义一个基础的模板引擎,命名叫smarty.class,php

       <?php
             //自定义一个模板引擎类,命名叫smarty
            class Smarty{
            private $vars=array();
        
             //给模板引擎中的变量赋值的方法
                 function assign($varname,$varvalue){
            
                 $this->vars[$varname]=$varvalue;    
    
    }
        //使用模板引擎中的定义的变量,替换指定的模板内容,方法中的参数为模板名称        
        function display($tplname){        
        
            $html=file_get_contents($tplname);
            
            //变量的正则表达式
            $zz=’/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/’;
            
            $rep=”<?php echo \$this->vars[‘\\1’];?>”;
            
            $newhtml=preg_replace($zz,$rep,$html);
            
            file_put_contents($tplname.’.php’,$newhtml);
            
            include $tplname.’.php’;
                            
    }
}
?>

3.主程序调用模板引擎,并使用模板引擎中的方法调用模板输出

     <?php
    include “smarty.class.php”;

    $smarty=new Smarty;

    //假定这是从数据库中获取到的数据内容,存在以下2个变量中;
    $tit=’我的生字表’;

    $cont=”我是一只放生千年的狐,千年修行千年孤独!”;

    //将这两个变量内容分配给模板中的变量(实际是先分配给模板引擎中定义的变量再由模板引擎执行替换模板中的变量内容)
    $smarty->assign(‘title’,$tit);

    $smarty->assign(‘content’,$cont);
    
    //调用指定的模板
    $smarty->display(‘demo.html’);

?>

原文链接:https://blog.csdn.net/living_ren/article/details/78542008

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

未经允许不得转载:起风网 » 自定义一个模板引擎
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录