升级上周的js模版引擎 支持include

本文介绍了一种自定义模板引擎的实现方式,包括如何解析模板字符串,处理变量、条件和循环等语法,以及如何将数据动态填充到模板中。通过具体示例展示了模板引擎的应用,如动态生成HTML元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

        var tpl = document.getElementById(str)
        if (!tpl) throw 'tpl:' + str + ' is not load'
        tpl = tpl.innerHTML

       var fCon = 'var p = [];function __require(id){ \
                    return function(data){ return etic(id).apply(data,arguments);} \
                };function __append(h){return p.push(h)}'

            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)
                    switch (scCon.charAt(0) ){
                        case '=':
                            scCon = ";p.push("+ scCon.substr(1) +");"
                            break
                        case '#':
                            scCon = ";__append(etic('"+ scCon.substr(1)  +"').apply(this));"
                            break
                        case '*':
                            scCon = ''
                            break
                    }

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

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

 

 

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

</ul>

</script>

</body>
<script>
var dul = {ul:['a','b'] , title:'tt'}
console.log(etic('ul' ,dul))
</script>
 <ul>    title: tt     title: aaa      <li>= a</li>     <li>= b</li>    </ul>  

还未支持异步加载....总感觉异步加载模版的话会变慢 - -!  模版的依赖应该在服务端拼装的时候能解决掉

转载于:https://www.cnblogs.com/vaal-water/archive/2013/03/25/2980495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值