为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 自定义 Smarty 模板引擎类

标签:
PHP

smarty模板引擎类简单工作原理

利用Smarty 模板引擎类对模板文件中的变量进行编译,编译过程其实就是利用正则表达式翻译成PHP文件。例如 模板文件中{$title} 利用正则表达式找到并替换成  <?php echo $this->vars['title'];?>

自定义 Smarty 模板引擎类 smarty.class.php页面

<?php

/*

 * 自定义Smarty模板引擎类

 */

        class Smarty{

            private $vars = array();

            //第一个向模板中分配变量 

            //有两个参数 一个参数是模板中的变量名,一个时分配给它的变量值

            public function assign($name,$value=null){

                        if($name != ' ')

                                $this->vars[$name]=$value;

            }

             

            //加载指定的模板 并显示

            //有一个参数是模板的文件名

            public function display($tplname){

                        $comfile = "./comps/".$tplname."_com.php";

                        $tplname = "./templates/".$tplname;

                        //编译文件不存在 或者模板文件有变化 才需要编译

                        if(!file_exists($comfile) || filemtime($tplname)>filemtime($comfile)){

                        $html = file_get_contents($tplname);

                         

                        //要替换的部分{title}

                        $reg = '/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/';

                        //变量正则表达式[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* 

                         

                        //替换后的部分<?php echo $this->vars['title'];?>

                        $rep = "<?php echo \$this->vars['\\1'];?>";

                         

                        $newhtml = preg_replace($reg, $rep, $html);    

                        file_put_contents($comfile, $newhtml);

                        }

                        include $comfile;

            }

             

        }

调用模板页面 index.php

<?php

header('content-type:text/html;charset=utf-8');

/*

 * 模版引擎

 * PHP 超文本预处理脚本语言

 * 自定义模板引擎

 * 

 */

 //包含模板引擎类

 include 'smart.class.php';

 //创建模板引擎对象

 $smarty = new Smarty();

 // 连接数据库

 //执行SQL语句

 // 这是从数据库获取的动态数据,需要在模板中显示

 $title = "This is a test";

 $content = "This is content ......";

  

 //第一个向模板中分配变量

 $smarty->assign('title', $title);

 $smarty->assign('content', $content);

 var_dump($smarty);

 //加载指定的模板 并显示

 $smarty->display('c.php');

模板文件页  c.php页面

<html>

<head>

<title>{$title}</title>

</head>

<body>

<h1>{$title}</h1>

<div>

{$content}

</div>

</body>

</html>


输出结果

object(Smarty)[1]  private 'vars' => 

    array (size=2)

      'title' => string 'This is a test' (length=14)

      'content' => string 'This is content ......' (length=22)

This is a test

This is content ......


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消