It is widely accepted that JSON is used to return data from the server, because it is short and easy to use. however, recreating data on the client is not a small problem, and it is often complicated to process data with javascript. especially for large batches of data with the same structure, such as tables, the processing method is not satisfactory. if you can have a template control, there will be a lot of things like asp.net Gridview or repeater on the server side. I recently saw a very good solution, which made it easy to use and I had to sigh for the author's elaborate design. this solution uses over 20 lines of code in the partition area to implement the work done by others using dozens or even hundreds of K js libraries. it is John Resig's Microtemplating engine. master Rick Strahl has an article dedicated to this (Client Templating with Jquery ). I will extract the core part here to facilitate Chinese learning.
The following program is the microtemplating engine.
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 (/[\ r \ t \ n]/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.html Encode () + "#> ";
}
How to use:
The Code is as follows:
ParseTemplate ($ ("# ItemTemplate" ).html (), {name: "rick", address: {street: "32 kaiea", city: "paia "}});
Template used by the above program:
The Code is as follows: