The meaning of using JS tempate:
Use JS to JSON data processing to generate HTML, if not complex can also, complex is not good to deal with, and let JS code looks special not elegant, maintenance of this code equals suicide Ah, don't talk about extensibility ...
Introduce a jquery template jquery.tmpl.js, using the following example:
- <! DOCTYPE html>
- <title></title>
- <meta http-equiv= "content-type" Content="text/html; Charset=utf-8 ">
- <script src="http://code.jquery.com/jquery.js" type="Text/javascript" ></script>
- <script src="jquery.tmpl.min.js" type="Text/javascript"> </script>
- <script>
- $(function () {
- VarWebsite= [{Url: ' Www.phpddt.com ',Name: php dot-point ' , Tags: [ ' Web Tutorial ' ' blog ' ] },{ Url: ' www.baidu.com ' , Name: ' Baidu ' , Tags: [ Search engine ' , ' Chinese search '
- //$ (' #myTemplate '). Tmpl (website). AppendTo (' #rows ');
- $(' #myTemplate '). Tmpl(website, {
- GetTags: function (separator) {
- return this . Data. Tags. Join(separator);
- }
- }). appendTo(' #rows ');
- });
- </script>
- <script id="myTemplate" type="Text/x-jquery-tmpl">
- <Tr><td>${< Span class= "PLN" > $data .}</td><td >${ $data .}</td><td >${ $item .td></tr
- </script>
- <body>
- <table cellspacing="0" cellpadding="3" border="1 ">
- <tbody id="Rows">
- </tbody>
- </table>
- </body>
Some common methods are:
$.template () method to compile a section of HTML into a template.
${}: Placeholder, another notation {{= field}}, you must note that the "=" number must be followed by a space.
$item,$data two properties:$item represents the current template; $data represents the current data.
{{each}} loop
{{ if}} and {{else}} logical judgment
{{html}}, replace placeholder with object property value directly as HTML code
{{Wrap}}, wrapper, this time no need to specify which element to use template, directly generate template wrapper
The $.tmplitem () method, using this method, can fetch the $item from the render element.
jquery template Jquery.tmpl.js tutorial (with jquery.tmpl.js download)