But in the client to reproduce the data is also a big problem, with JavaScript processing often encounter very cumbersome things. In particular, large quantities of data with the same structure, such as tables, are not handled satisfactorily. If you can have a template control, like a server-side asp.net A GridView or repeater is much better. Recently saw a very good solution, let me in the use of convenience at the same time have to make a sigh for the author's exquisite design. The solution uses just more than 20 lines of code, The realization of others to use dozens of or even hundreds of K JS Library to do the work. It is John Resig's microtemplating engine. Master Rick Strahl has an article devoted specifically to this (Client templating with Jquery). I am here to extract the core parts to facilitate the study of the people.
The following procedure is Microtemplating engine.
Copy Code code as follows:
var _tmplcache = {}
this.parsetemplate = function (str, data) {
<summary>
Client side template parser that uses <#= #> and <# code #>.
and # # code blocks for template expansion.
Note:chokes on single quotes in some situations
Use ' for literals in-text and avoid any single quote
attribute delimiters.
</summary>
<param name= "str" type= "string" >the text of the template to expand</param>
<param name= "Data" type= "var" >
Any of the data is merged. Pass an object and
That object ' s properties are visible as variables.
</param>
<returns type= "string"/>
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, "', $, '")
. 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 code as follows:
Parsetemplate ($ ("#ItemTemplate"). HTML (), {name: "Rick", Address: {street: "Kaiea", City: "Paia"});
The template used for the above program:
Copy Code code as follows:
<script id= "ItemTemplate" type= "text/html" ><div><div><#= name #></div><div> <#= Address.street #></div> </div></script>
If you want to use loops:
Copy Code code as follows:
$.each (Dataarray,function (Index,dataitem) {
Parsetemplate ($ ("#ItemTemplate"). html (), DataItem);
})
It's simple and ingenious, isn't it?