日期:2014-05-16  浏览次数:20349 次

javascript 模板替换函数
支持数据多级嵌套和数组:
var applyTpl = (function(){
    var reg = /\{([\w\.]*)\}/g;

    var regArr = /<#for\s+(\w+)>(.*?)<\/for#>/g,
        regArrIdx = /\{#i\}/g,
        regArrVal = /\{#val\}/g;
    function getVal(key,data){
        var arr = key.split("."),
            val = data;
        while(arr[0] && val){
            val = val[arr.shift()];
        }
        if(val === null || typeof val === "undefined"){
            val = "";
        }
        return val;
    }

    //处理数组
    function compileArray(tpl,data){
        tpl = tpl.replace(regArr,function(){
            var tmp = "",
                obj = getVal(arguments[1],data);
            if(typeof obj === "object" &&  obj instanceof Array){
                for(var i=0,len = obj.length; i<len; i++){
                    tmp += replaceFn(arguments[2],obj[i]);
                    tmp = tmp.replace(regArrIdx,i).replace(regArrVal,obj[i]);
                }
            }
            return tmp;
        });
        return tpl;
    }

    function replaceFn(tpl,data){
        tpl = compileArray(tpl,data);
        tpl = tpl.replace(reg,function(){
            return getVal(arguments[1],data);
        });

        return tpl;
    };
    return replaceFn;
})();

//example:
var str = '{tel}{userName}aaaa{tel}aaaa<ul><#for shopList><li>{#i}:{commodityId}</li></for#></ul>aaaaaaaa<#for arr><li>{#i}:{#val}</li></for#>';
var obj = {"userName":"测试","tel":"13800138010","remark":"","arr":['X','Y'],"address":"4-42-110","shopList":[{"commodityId":"58","countToBuy":1}],"coin":11};


applyTpl(str,obj)