Home > Web Front-end > JS Tutorial > body text

JSON JQUERY template implementation instructions_jquery

WBOY
Release: 2016-05-16 18:23:57
Original
1072 people have browsed it

However, reproducing data on the client side is also a big problem. It is often very cumbersome to process it with JavaScript. Especially for large batches of data with the same structure, such as tables, the processing method is not satisfactory. If there is a template control, Something like the server-side asp.net Gridview or repeater is much better. Recently I saw a very excellent solution, which made me sigh for the author's exquisite design while being easy to use. This solution It took only a few dozen lines of code to achieve what others would do using tens or even hundreds of K of js libraries. It is John Resig's Microtemplating engine. Master Rick Strahl has an article that describes this in detail ( Client Templating with Jquery). Here I extract the core part to facilitate the learning of Chinese people.

The following program is the microtemplating engine.

Copy the code The code is as follows:

var _tmplCache = {}
this.parseTemplate = function(str, data) {
///
/// Client side template parser that uses <#= # > and <# code #> expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
// / use ' for literals in text and avoid any single quote
/// attribute delimiters.
///

/// The text of the template to expand
///
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
///
///
var err = "";
try {
var func = _tmplCache[str];
if (!func) {
var strFunc =
"var p=[],print=function() {p.push.apply(p,arguments);};"
"with(obj){p.push('"

str.replace(/[rtn]/g, " ")
.replace(/'(?=[^#]*#>)/g, "t")
.split("'").join("\'")
.split ("t").join("'")
.replace(/<#=(. ?)#>/g, "',$1,'")
.split("< #").join("');")
.split("#>").join("p.push('")
"');}return p.join('' );";

//alert(strFunc);
func = new Function("obj", strFunc);
_tmplCache[str] = func;
}
return func(data);
} catch (e) { err = e.message; }
return "< # ERROR: " err.htmlEncode() " # >";
}

How to use:
Copy code The code is as follows:
parseTemplate($("# ItemTemplate").html(),{ name: "rick", address: { street: "32 kaiea", city: "paia"} } );


Template used in the above program:
Copy code The code is as follows:
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template