Smarty模板原理

来源:互联网 发布:艾媒咨询数据 编辑:程序博客网 时间:2024/06/03 19:08

**************************************************

mysmarty.class.php

    <?php
    //自定义Smarty模拟类
    class MySmarty{
        private $data = array();
        //向模板中放置变量方法
        public function assign($name,$value){
            $this->data[$name] = $value;
        }
        //加载并输出模板
        public function display($tpl){
            //获取模板内容
            $text = file_get_contents($tpl);
            //遍历属性data,做信息替换
            foreach($this->data as $k=>$v){
                $text = str_replace('{$'.$k.'}',$v,$text);
            }
            echo $text;
            //生成静态缓存
            file_put_contents($tpl.".html",$text);
        }

    }

**************************************************

demo.php
    <?php
    $title = "自定义Smarty模板引擎";
    $content = "Smarty模板引擎原理";
    require("mysmarty.class.php");
    $smarty = new MySmarty();
    $smarty->assign("title",$title);
    $smarty->assign("content",$content);

    $smarty->display("demo.tpl");

**************************************************

demo.html
    <!DOCTYPE HTML>
    <html>
        <head>
            <title>{$title}</title>
            <meta charset="utf-8">
        </head>
        <body>
            <h3>{$title}</h3>
            <h4>{$content}</h4>
        </body>
    </html>
原创粉丝点击