一个简单的javascript前端模版引擎

(function(window,undefined){
    var cache = {};
    window.etic =  function (str, data){
        if (!cache[str] ){
            var tpl = $(str)[0].innerHTML

            var fCon = 'var p = [];'

            while (true){
                var pst = tpl.indexOf('<?')
                if (pst < 0) {
                    fCon += "p.push('"+ tpl.replace(/[\r\t\n]/g, " ") +"');return p.join('');"
                    break
                    }
                    var pend = tpl.indexOf('?>' ,pst)
                    var preHtml = tpl.substr(0,pst)
                                    .replace(/[\r\t\n]/g, " ")
                    var scCon = tpl.substring(pst+2 , pend)
                                   .replace(/\n/g,';')
                    tpl = tpl.substr(pend+2)
                    if ('=' == scCon.charAt(0) )
                        scCon = ";p.push("+ scCon.substr(1) +");"

                    fCon += "p.push('"+ preHtml +"');" + scCon

                    }
             cache[str] =new Function('',fCon)
           
        }
    var fn = cache[str]
     return data ? fn.apply( data ) :fn
    
 }
})(this)

 

或者更简单的(这个速度略快,基本代码来自John Resig

(function(window,undefined){
    var cache = {};
    window.etic =  function (str, data){
        if (!cache[str] ){
            var tpl = $(str)[0].innerHTML

 
            tpl = tpl
            .replace(/[\r\t\n]/g, " ")
           .split("<\?").join("\t")
            .replace(/((^|\?>)[^\t]*)'/g, "$1\r")
            .replace(/\t=(.*?)\?>/g, "',$1,'")
            .split("\t").join("');")
            .split("\?>").join("p.push('")
            .split("\r").join("\\'")
            cache[str] = new Function("",
                "var p=[];p.push('" + tpl + "');return p.join('');");
        }
    return data ? cache[str].apply( data ): fn

 }
})(this)

 

模版内容:

<script type=text/plain id=ul>
<ul>
title: <?= this.title ?>
<? var i = 0 ,j = this.ul.length;
for (;i < j ;i++){
?>
<li>= <?= this.ul[i] ?></li>
<? }?>

</ul>

</script>

  

调用方法

 

var dul = {ul:['a','b'] , title:'tt'}
console.log(etic('#ul' ,dul))

=》

 <ul>  title: tt     <li>= a</li>     <li>= b</li>    </ul>  

  

 

posted on 2013-03-21 21:07  雨弓  阅读(216)  评论(0编辑  收藏  举报