+ -
当前位置:首页 → 问答吧 → 自己写模板引擎

自己写模板引擎

时间:2008-05-04

来源:互联网

template.php
复制PHP内容到剪贴板
PHP代码:

<?php
/**
* @filename :firephp.php
* @author :xusong lie
* @e-mail :[email protected]
* @date :2008-05-03
*/

class Firephp {
    var $tpl_vars;
    var $template_c = 'template_c/';

    function Firephp() {
        $this->tpl_vars = array();
    }//end of firephp()

    function assign($key,$val=null) {
        if(!isset($key)) return false;
        if(is_array($key) && !isset($val)) {
            if(sizeof($this->tpl_vars) > 0) {
                $this->tpl_vars = array_merge($this->tpl_vars,$key);
            } else {
                $this->tpl_vars = $key;
            }
        } else {
            $this->tpl_vars[$key] = $val;
        }
        return true;
    }//end of assign()

    function parse($filename) {
        if(!file_exists($filename)) die('Template is not exists.');
        $content = '<?php /*copyright:2008 ; author:xusong lie*/ ?>'."\n";
        $content .= file_get_contents($filename);
        $pattern = "/\\$[a-zA-Z_]{1,}[a-zA-Z0-9_]{0,}/";
        preg_match_all($pattern,$content,$matchs);

        foreach($matchs[0] as $match) {
            if(!isset($this->tpl_vars[substr($match,1,strlen($match))])) die("Variable {$match} had not defined.");
        }

        $content = preg_replace("/\\{\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\\}/",'<?php echo $this->tpl_vars["\\1"]; ?>',$content);
        //start if
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}==\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] == $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] > $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] >= $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] < $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] <= $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}!=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] != $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}===\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php if($this->tpl_vars["\\1"] === $this->tpl_vars["\\2"]):?>',$content);

        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}==\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] == \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] > \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>=\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] >= \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] < \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<=\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] <= \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}!=\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] != \\2):?>',$content);
        $content = preg_replace('/\{if \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}===\s{0,}(\S{1,})\}/','<?php if($this->tpl_vars["\\1"] === \\2):?>',$content);
        $content = preg_replace('/\{if \S{1,}\}/','<?php if(\\1):?>',$content);
        //end if
        
        //start else if
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}==\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] == $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] > $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] >= $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] < $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] <= $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}!=\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] != $this->tpl_vars["\\2"]):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}===\s{0,}\\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php else if($this->tpl_vars["\\1"] === $this->tpl_vars["\\2"]):?>',$content);

        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}==\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] == \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] > \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}>=\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] >= \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] < \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}<=\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] <= \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}!=\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] != \\2):?>',$content);
        $content = preg_replace('/\{elseif \\$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\s{0,}===\s{0,}(\S{1,})\}/','<?php else if($this->tpl_vars["\\1"] === \\2):?>',$content);
        $content = preg_replace('/\{if \S{1,}\}/','<?php if(\\1):?>',$content);
        //end else if

        //start foreach
        $content = preg_replace('/\{section \$([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,}) in @([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php foreach(\$this->tpl_vars["\\1"] as \$\\2): ?>',$content);
        $content = preg_replace('/\{@([a-zA-Z_]{1,}[a-zA-Z0-9_]{0,})\}/','<?php echo \$\\1; ?>',$content);
        //end foreach
        $content = preg_replace('/\{include ([^\{\}]+)\}/','<?php include("\\1"); ?>',$content);
        /*
        $content = preg_replace('/\{foreach (\S{1,})\}/','<?php foreach(\\1):?>',$content);
        */
        $content = str_replace(array('{else}','{/if}','{/section}'),array('<?php else: ?>','<?php endif; ?>','<?php endforeach; ?>'),$content);

        $fp = fopen($this->template_c.md5($filename).'.php','w');
        fwrite($fp,$content);
    }//end of parse();

    function display($filename) {
        $cacheFile = $this->template_c.md5($filename).'.php';
        if(file_exists($cacheFile)) {
            if(filemtime($filename) > filemtime($cacheFile)) {
                $this->parse($filename);
            }
        } else {
            $this->parse($filename);
        }
        include_once($cacheFile);
    }//end of display()
}
?>

测试页面
复制PHP内容到剪贴板
PHP代码:

<?php
include_once("template.php");
$tpl = new Firephp();
$tpl->assign('a','hello');
$tpl->assign('b','world');
$tpl->assign('c','hello');
$tpl->assign('array',array('t','o','n','y'));
$tpl->display('tpl.html');
?>

模板页面
复制PHP内容到剪贴板
PHP代码:
{$a} {$b} {if $a == 'hello'} hello {/if} {if $b != $a} world {/if}

{section $array in @a}
{@a}
{/section}

输出:hello world  hello   world tony

作者: liexusong   发布时间: 2008-05-03

一个标签要来来回回的折腾好多次啊。

作者: fhjr999   发布时间: 2008-05-03

支持一下。

作者: luzhou   发布时间: 2008-05-04

自己写框架

作者: 七月十五   发布时间: 2008-05-04

  支持一下。

作者: 特蓝克斯   发布时间: 2008-05-04

引用:
原帖由 七月十五 于 2008-5-4 08:12 发表
自己写框架
哈哈,我的小框架早就出来了。虽然根本称不上是框架。

作者: fhjr999   发布时间: 2008-05-04

学习……

作者: libaiyi   发布时间: 2008-05-04

过几天 俺发一个模板引擎吧 呼呼~

作者: haierspi   发布时间: 2008-05-04



[ 本帖最后由 七月十五 于 2008-5-5 15:30 编辑 ]

作者: 七月十五   发布时间: 2008-05-05

总的来说就是变量替换~~~~麻烦...

作者: xyiyo   发布时间: 2008-05-05

本人也觉得模板引擎没必要一定用!额外开销很大~而且功能有所限制!所以把模板引擎换成模板类了~
复制PHP内容到剪贴板
PHP代码:

<?php
/**
 * Template
 *
 * @package 
 * @author xusong Lie
 * @copyright 2008
 * @version 1.0
 * @access public
 */
class Template {
    var $tpl_vars;
    var $templatePath;
    
    function Template() {
        $this->tpl_vars = array();
        $this->templatePath = 'templates/';
    }
    
    function setTemplatePath($path) {
        if(is_dir($path))
            $this->templatePath = $path;
        else
            die($path.' is not a right path.');
    }
    
    function assign($key,$val=null) {
        if(!isset($key)) return false;
        if(is_array($key) && !isset($val)) {
            if(sizeof($this->tpl_vars) > 0) {
                $this->tpl_vars = array_merge($this->tpl_vars,$key);
            } else {
                $this->tpl_vars = $key;
            }
        } else {
            $this->tpl_vars[$key] = $val;
        }
        return true;
    }//end of assign()
    
    function display($filename) {
        $tpl_file = $this->templatePath.$filename;
        if(!file_exists($tpl_file)) die('Template file is not exists.');
        if(sizeof($this->tpl_vars) > 0) {
            foreach($this->tpl_vars as $var => $value) {
                $$var = $value;
            }
        }
        ob_start();
        include_once($tpl_file);
        $content = ob_get_contents();
        ob_end_clean();
        
        echo $content;
        return true;
    }//end of display()
}

?>

我觉得这个类更好用~~~谢谢大家支持!

作者: liexusong   发布时间: 2008-05-05

所谓模板,核心就是读模板文件内容到一个字符串,然后替换定义的字符最后输出

作者: netbuddy   发布时间: 2008-05-06

没意思,随手贴手头的一段
复制PHP内容到剪贴板
PHP代码:

<?
require_once("***"); 
TagFeather::OutBegin();
/*这里是公司的代码, 算了就不贴了*/
/////////////////////////////
$file=__FILE__;
TagFeather::Template($file);
return;
TagFeather::OutEnd();
?>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<body>
<div parser:notag="yes" parser:notext="yes">
    <div php:byvisible="<?=$rs['name']?>">【任务名称】</div>
    <div php:byvisible="<?=$rs['title']?>">【任务标题】</div>
</div>
<form method="post" >
<input type="hidden" name="id" value="<?=$id?>" />
要测试的任务:<span>【任务名称】</span><br />
任务标题:<span>【任务标题】</span><br />
测试邮件地址
<input type="text" name="address" value="" /><br />
<input type="submit" value="发送" />
</form>
</body>
</html>
生成的缓存文件 ,有空去对比 smarty 的缓存文件,看看 smarty 的效率为什么会那么低了
复制PHP内容到剪贴板
PHP代码:

<?php 
//Cache By TagFeather Version $Id: tagfeather.inc.php 23 2008-01-30 15:58:56Z dvaknheo $
//source ****.php Time 2008-05-07 02:32:17 MD5 
//In ***.cache.php Time 2008-05-07 02:32:18 MD5 9c274f0c2c05e0c4dd333c9e2f261b01 (MD5 no include this server block)
//timecost:0.015354156494141
if(!$GLOBALS['TF_IN_CACHE']){exit('TagFeather:permission deny');}
?><?
require_once("***");
if(!isset($GLOBALS['TF_IN_CACHE'])){
TagFeather::OutBegin();
/*这里是公司的代码, 算了就不贴了*/
/////////////////////////////
$file=__FILE__;
TagFeather::Template($file);
return;
}//}if(!isset($GLOBALS['TF_IN_CACHE'])
 TagFeather::OutEnd();
?>
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<body>

<form method="post">
<input type="hidden" name="id" value="<?=$id?>" />
要测试的任务:<span><?=$rs['name']?></span><br />
任务标题:<span><?=$rs['title']?></span><br />
测试邮件地址
<input type="text" name="address" value="【测试地址】" /><br />
<input type="submit" value="发送" />
</form>
</body>
</html>

作者: dvaknheo   发布时间: 2008-05-07

好东西,谢谢lz的分享。学习了

作者: ocean2000   发布时间: 2008-05-07

留下个脚印!
慢慢研究一下!
谢谢lz分享!!

作者: naodai   发布时间: 2008-05-07

热门下载

更多