search
Homephp教程PHP开发Detailed explanation of the use of jquery.tmpl, a framework for generating HTML using templates

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 = "<li>Some content: ${item}.<br/>" 
+ " More content: ${myValue}.</li>";
$.template( "movieTemplate", markup );
<script id="movieTemplate" type="text/x-jquery-tmpl"> 
<li><b>${Name}</b> (${ReleaseYear})</li> 
</script>

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:

<div id="div_demo">
</div>
<script id="demo" type="text/x-jquery-tmpl">
    <div style="margin-bottom:10px;">
      <span>${ID}</span>
      <span style="margin-left:10px;">{{= Name}}</span>
      <span style="margin-left:10px;">${Number(Num)+1}</span>
      <span style="margin-left:10px;">${Status}</span>
    </div>
</script>
<script type="text/javascript">
  var users = [{ ID: &#39;think8848&#39;, Name: &#39;Joseph Chan&#39;, Num: &#39;1&#39;, Status: 1 }, { ID: &#39;aCloud&#39;, Name: &#39;Mary Cheung&#39;, Num: &#39;2&#39;}];
  $("#demo").tmpl(users).appendTo(&#39;#div_demo&#39;);
</script>

{{each}} provides loop logic, and $value also accesses iteration variables You can customize the iteration variable (i, value)

Example:

<div id="div_each">
</div>
<script id="each" type="text/x-jquery-tmpl"> 
    <h3 id="users">users</h3>
    {{each(i,user) users}}
        <div>${i+1}:{{= user.name}}</div>
        {{if i==0}}
            <h4 id="group">group</h4>
            {{each(j,group) groups}}
                <div>${group.name}</div>
            {{/each}}
        {{/if}}
    {{/each}}
    <h3 id="depart">depart</h3>
    {{each departs}}
        <div>{{= $value.name}}</div>
    {{/each}}
</script> 
<script type="text/javascript">
  var eachData = { users: [{ name: &#39;jerry&#39; }, { name: &#39;john&#39;}], groups: [{ name: &#39;mingdao&#39; }, { name: &#39;meihua&#39; }, { name: &#39;test&#39;}], departs: [{ name: &#39;IT&#39;}] };
  $("#each").tmpl(eachData).appendTo(&#39;#div_each&#39;);
</script>

{{if }} {{else}} provides branch logic {{else}} which is equivalent to else if

Example:

<div id="div_ifelse"></div>
<script id="ifelse" type="text/x-jquery-tmpl"> 
    <div style="margin-bottom:10px;"><span>${ID}</span><span style="margin-left:10px;">{{= Name}}</span>
        {{if Status}}
            <span>Status${Status}</span>
        {{else App}}
            <span>App${App}</span>
        {{else}}
            <span>None</span>
        {{/if}}
    </div>
</script> 
<script type="text/javascript">
  var users = [{ ID: &#39;think8848&#39;, Name: &#39;Joseph Chan&#39;, Status: 1, App: 0 }, { ID: &#39;aCloud&#39;, Name: &#39;Mary Cheung&#39;, App: 1 }, { ID: &#39;bMingdao&#39;, Name: &#39;Jerry Jin&#39;}];
    $("#ifelse").tmpl(users).appendTo(&#39;#div_ifelse&#39;);
</script>

{{html }} Output variable html, but without html encoding, suitable for outputting html code

instance

<div id="div_html"></div>
<script id="html" type="text/x-jquery-tmpl"> 
    <div style="margin-bottom:10px;">
    <span>${ID}</span>
    <span style="margin-left:10px;">{{= Name}}</span>
      ${html}
      {{html html}}
    </div>
</script> 
<script type="text/javascript">
  var user = { ID: &#39;think8848&#39;, Name: &#39;Joseph Chan&#39;, html: &#39;<button>html</button>&#39; };
   $("#html").tmpl(user).appendTo(&#39;#div_html&#39;);
</script>

{{tmpl}} nested template

instance

<div id="tmpl"></div>
<script id="tmpl1" type="text/x-jquery-tmpl">
    <div style="margin-bottom:10px;">
      <span>${ID}</span>
      <span style="margin-left:10px;">{{tmpl($data) &#39;#tmpl2&#39;}}</span>
    </div>     
</script>
<script id="tmpl2" type="type/x-jquery-tmpl">
    {{each Name}}${$value}  {{/each}}   
</script>
<script type="text/javascript">
  var users = [{ ID: &#39;think8848&#39;, Name: [&#39;Joseph&#39;, &#39;Chan&#39;] }, { ID: &#39;aCloud&#39;, Name: [&#39;Mary&#39;, &#39;Cheung&#39;]}];
   $("#tmpl1").tmpl(users).appendTo(&#39;#tmpl&#39;);
</script>

{{wrap}}, wrapper

instance

<div id="wrapDemo">
    </div>
<script id="myTmpl" type="text/x-jquery-tmpl">
    The following wraps and reorders some HTML content:
    {{wrap "#tableWrapper"}}
        <h3 id="One">One</h3>
        <div>
            First <b>content</b>
        </div>
        <h3 id="Two">Two</h3>
        <div>
            And <em>more</em> <b>content</b>...
        </div>
    {{/wrap}}
    </script>
<script id="tableWrapper" type="text/x-jquery-tmpl">
    <table cellspacing="0" cellpadding="3" border="1"><tbody>
        <tr>
            {{each $item.html("h3", true)}}
                <td>
                    ${$value}
                </td>
            {{/each}}
        </tr>
        <tr>
            {{each $item.html("div")}}
                <td>
                    {{html $value}}
                </td>
            {{/each}}
        </tr>
    </tbody></table>
    </script>
 <script type="text/javascript">
        $(function () {
            $(&#39;#myTmpl&#39;).tmpl().appendTo(&#39;#wrapDemo&#39;);
        });
    </script>

$ data $item $item represents the current template; $data represents the current data.

Example:

<div id="div_item_data"></div>
<script id="item_data" type="text/x-jquery-tmpl"> 
     <div style="margin-bottom:10px;">
    <span>${$data.ID}</span>
    <span style="margin-left:10px;">${$item.getName(" ")}</span>
   </div>
</script> 
<script type="text/javascript">
   var users = [{ ID: &#39;think8848&#39;, Name: [&#39;Joseph&#39;, &#39;Chan&#39;] }, { ID: &#39;aCloud&#39;, Name: [&#39;Mary&#39;, &#39;Cheung&#39;]}];
     $("#item_data").tmpl(users,
                {
                getName: function (spr) {
                   return this.data.Name.join(spr);
                }
                }).appendTo(&#39;#div_item_data&#39;);
</script>

$.tmplItem() method, using this method, you can get $item from the rendered element

Instance

<script type="text/javascript">
  $(&#39;#demo&#39;).delegate(&#39;div&#39;, &#39;click&#39;, function () {
                var item = $.tmplItem(this);
                alert(item.data.Name);
            });
</script>



More frameworks for generating HTML using templates Please pay attention to the PHP Chinese website for related articles about the use of jquery.tmpl!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.