用php自己写的模版引擎 (未完善,主要是思路)

IT-Pony 2016-03-29 AM 406℃ 0条
<?php

class Template{
    public function Tpl($_argvs,$_tmp_file,$_tmp_left = '{',$_tmp_right = '}'){
        //将模版文件读成数组
        $_template = file($_tmp_file);
        //初始化数据变量
        $_template_tmp = '';
        //循环文件数组
        foreach ($_template as $key => $val) {
            $_template_replace_num = preg_match_all('/\\'.$_tmp_left.'([^{}]+)\\'.$_tmp_right.'/', $val, $matches);
            if($_template_replace_num > 0){
                //循环匹配内容
                foreach ($matches[0] as $k => $v) {
                    //变量和循环名转换
                    $Key =  $matches[1][$k];
                    //判断是不是变量或者循环的标识
                    if(isset($_argvs[$Key]) || $Key == 'i' || $Key == 'key' || $Key == 'value' || $Key == 'k' || $Key == 'v' || $Key == 'val'){
                        $val = str_replace($v,'<?php echo($'.$Key.')?>',$val);
                    }
                    //循环开始
                    if(strstr($Key,'if(') || strstr($Key,'foreach(') || strstr($Key,'while(') || strstr($Key,'for(')){
                        $val = str_replace($v,'<?php '.$Key.':?>',$val);
                    }
                    //条件控制
                    if(strstr($Key,'else')){
                        $val = str_replace($v,'<?php '.$Key.':?>',$val);
                    }
                    //循环关闭
                    if(strstr($Key,"if") == 'if' || strstr($Key,"foreach") =='foreach'||  strstr($Key,"while") == 'while' ||  strstr($Key,"for") == 'for'){
                        $val = str_replace($v,'<?php end'.trim($matches[1][$k],'/').'?>',$val);
                    }
                }
            }
            $_template_tmp.= $val;
            file_put_contents('./cache/index.html',$_template_tmp);
        }
        return './cache/index.html';
    }
}

$tmp = new Template;

@include($tmp -> Tpl($data,'index.html'));
标签: php

非特殊说明,本博所有文章均为博主原创。

评论啦~