Dynamic requesting data to update the page is a very common method nowadays, such as paging dynamic loading of blog comments, rolling loading and scheduled request loading of Weibo, etc.
In these cases, the data returned by the dynamic request is usually either assembled HTML, JSON or XML. In short, the data is not assembled on the browser side, but on the server side. However, returning HTML is not cost-effective in terms of transmission volume, and in terms of web transmission, JSON is now used more than XML.
A very troublesome part of generating HTML based on JSON on the browser side is that it's okay when the structure is not complicated, but once the structure is complicated, it becomes a nightmare. You need to be very careful to write JavaScript code that is almost impossible to maintain.
Therefore, some frameworks that use templates to generate HTML have appeared one after another. jquery.tmpl is one of them. Let’s introduce the usage of jquery.tmpl in detail
The following will focus on the usage:
First, let’s introduce the template and data , Needless to say, these two are definitely indispensable. There are two ways to define templates. The specific codes are given below
var markup = "
In this way, two templates are defined. The former one is written in script, and the latter one is written in html. The
data inside is json
Start rendering the template below
$( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" ); $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
Note: movies is a json data array
var movies = [ { Name: "The Red Violin", ReleaseYear: "1998" }, { Name: "Eyes Wide Shut", ReleaseYear: "1999" }, { Name: "The Inheritance", ReleaseYear: "1976" } ];
The common tags of jquery.tmpl are:
${}, {{each}}, {{ if}}, {{else}}, {{html}}
Uncommon tags
{{=}},{{tmpl}} and {{wrap}}.
${} is equivalent to {{= }} is the output variable ${} and you can also put expressions in it (there must be a space between = and the variable, otherwise it will be invalid)
Example:
{{each}} provides loop logic, and $value also accesses iteration variables You can customize the iteration variable (i, value)
Example:
{{if }} {{else}} provides branch logic {{else}} which is equivalent to else if
Example:
{{html }} Output variable html, but without html encoding, suitable for outputting html code
instance
{{tmpl}} nested template
instance
{{wrap}}, wrapper
instance
$ data $item $item represents the current template; $data represents the current data.
Example:
$.tmplItem() method, using this method, you can get $item from the rendered element
Instance
More frameworks for generating HTML using templates Please pay attention to the PHP Chinese website for related articles about the use of jquery.tmpl!