At my last blog 《Extension String:Format》 I already extension string to deal with complex string replace.app
This method already based a Template Engine.ide
Next step for a Template Engine is add parameter replace and call method.oop
To sperate UI Render and Data Logic.ui
As usual here is the core code.this
// class TemplateBuilder var TemplateBuilder = function (owner) { //constructor this.owner = owner; } TemplateBuilder.prototype = (function () { //private var methodMapping = { Test:function(value){ return value+" run in test method" } } //deal method mapping var BuildTemplateHtml = function (templateHtml, paramObj) { var exp = new RegExp("{([^{]*?)}", "ig"); var returnValue = templateHtml; var result = exp.exec(returnValue); while (result) { //loop till there is no template pattern string left result = result[1]; var replaceSetting = { key: result, value: "" } var splits = result.split(":"); var objType = splits[0]; var paramName = splits[1]; var mappingMethodStr = splits[2]; var obj = null; //get param object if(paramObj&¶mObj[objType])obj=paramObj[objType]; var value = null; if (obj) { value = TemplateHelper.GetParam(obj, paramName); } //check is setting template deal method if (mappingMethodStr) { var paramExp = /\((.*?)\)/ig; var mappingMethodName = mappingMethodStr.replace(paramExp, ""); var method = methodMapping[mappingMethodName]; if (method) { var params = [value]; var methodParam = paramExp.exec(mappingMethodStr); if (methodParam && methodParam.length > 1) { methodParam = methodParam[1]; params = params.concat(methodParam.split(","));//get param } value = method.apply(this, params);//call method } } if (!value) { value = "" } replaceSetting.value = value; ; returnValue = returnValue.Format(replaceSetting); exp.lastIndex = 0; result = exp.exec(returnValue); } return returnValue; } var returnValue = { //public owner: null, BuildTemplate: function (strTemplate, paramObj) { return BuildTemplateHtml.call(this, strTemplate, paramObj); } }; return returnValue; })();
In previous code I used a help class TempateHelperprototype
Here is the codecode
var TemplateHelper = { GetParam: function (sourceObj, strParam) { var strs = strParam.split("."); var returnValue = null; for (var i = 0; i < strs.length; i++) { if (!returnValue) { returnValue = sourceObj; } returnValue = returnValue[strs[i]]; if (!returnValue) { break; } } if (!returnValue) { returnValue = $.trim(returnValue); } return returnValue; } }
Demo
orm