Home >Web Front-end >JS Tutorial >Detailed explanation of the use of jquery.tmpl, a framework for generating HTML using templates_jquery
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 is okay when the structure is not complex, 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 focuses on how to use it:
First of all, let’s introduce templates and data. Needless to say, these two are definitely indispensable
There are two ways to define templates. The specific code is given below
$.template( "movieTemplate", markup );
In this way, two templates are defined, the former is written in script, and the latter is written in html
Data uses json
Start rendering the template below
Note: movies is a json data array
Several common tags of jquery.tmpl are:
${}, {{each}}, {{if}}, {{else}}, {{html}}
Uncommonly used tags
{{=}},{{tmpl}} and {{wrap}}.
${} is equivalent to {{=}} and is an output variable. Expressions can also be placed in ${} (there must be a space between = and the variable, otherwise it will be invalid)
Example:
{{each}} provides loop logic, $value accesses the iteration variable. You can also customize the iteration variable (i, value)
Example:
{{if }} {{else}}提供了分支逻辑 {{else}} 相当于else if
示例:
{{html}} 输出变量html,但是没有html编码,适合输出html代码
实例
{{tmpl}} 嵌套模版
实例
{{wrap}},包装器
实例
$data $item $item代表当前的模板;$data代表当前的数据。
实例:
$.tmplItem() method, using this method, you can retrieve $item
from the rendered elementExample