一个简单的js模板引擎
作者:admin 日期:2013-06-06
自己写来快速生成html代码用的, 因为要求比较简单,也就没用网上的模板解析引擎了
//charset gbk /* 快速模板处理 * author: gaohuia 2013.06.05 */ function Render(html, config) { /* 模板 */ this.html = html; /* 对默认值进行覆盖 */ if (config) { for (var key in config) { this.config[key] = config[key]; } } } Render.prototype = { /* 配置 */ config: { allowEmpty: false /*设置值是否为空字符*/ }, html: "', htmlCollection: [], varCollection: [], onRenderTag: function(tag, rowData) {}, /* * 渲染所有数据,data被视为一个行数据的集合,如果data是一个对象,则自动作为一个行对象来渲染 */ renderData: function(data) { /* * 分析html文本, 提取变量 */ this.prepareHtml(); if (data instanceof Array) { var htmls = []; for (var i = 0; i < data.length; i++) { htmls.push(this.fetchRow(data[i])); } return htmls.join(''); } else if (data instanceof Object) { return this.fetchRow(data); } else { throw "data必需是一个Object或Array的一个实例"; } }, /* * 将一行视为一个模板渲染的对象 */ fetchRow: function(rowData) { var htmlCollection = this.htmlCollection; var varCollection = this.varCollection; /**/ var htmls = []; for (var i = 0; i < varCollection.length; i++) { var varTag = varCollection[i]; /* * 变量在字典中存在的情况 */ if (rowData.hasOwnProperty(varTag.varName) && rowData[varTag.varName] != null && (rowData[varTag.varName] != '' || this.config['allowEmpty'])) { varTag.varValue = rowData[varTag.varName]; this.onRenderTag(varTag, rowData); } else { if (varTag.varAttr.hasOwnProperty('default')) { varTag.varValue = varTag.varAttr['default']; } else { varTag.varValue = ''; } } htmls.push(htmlCollection[i]); htmls.push(varTag.varValue); } htmls.push(htmlCollection[i]); return htmls.join(''); }, prepareHtml: function() { var html = this.html; if (html.length == 0) return; var exp = /\{\$(.*?)\}/g; var varCollection = []; var htmlCollection = []; var arr = null; var lastIndex = 0; while ((arr = exp.exec(html)) != null) { var varAttr = {}; var varFull = arr[1]; var tagFull = arr[0]; /* * 对多于空格进替换,方便后面提取标签属性 */ varFull = varFull.replace(/\s+/g, " "); var tmp = varFull.split(' '); var varName = tmp[0]; for (var i = 1; i < tmp.length; i++) { var attrPair = tmp[i].split('='); var attrName = attrPair[0]; var attrValue = attrPair[1].replace(/[\"\']/g, ""); varAttr[attrName] = attrValue; } /* * 一个单独的标签, 用户可以根据标签的属性对标签的值做不同的处理 */ var varSingle = { tagFull: tagFull, varName: varName, varFull: varFull, varValue: '', varAttr: varAttr } /* 为变量设置默认值 */ if (varSingle.varAttr.hasOwnProperty('default')) { varSingle.varValue = varSingle.varAttr['default']; } varCollection.push(varSingle); var htmlPiece = html.substr(lastIndex, arr.index - lastIndex); htmlCollection.push(htmlPiece); /* * 准备下一次标签寻找 */ lastIndex = arr.index + arr[0].length; } htmlPiece = html.substr(lastIndex); htmlCollection.push(htmlPiece); this.htmlCollection = htmlCollection; this.varCollection = varCollection; } }
评论: 0 | 查看次数: 6167