Jtemplate for JavaScript front-end HTML template engine

Source: Internet
Author: User

Recent projects have used Jtemplate, a client-side JavaScript-based template engine that binds data to JSON objects. I used to display the data list on the page when I like to use the Repeater control, because it is the most lightweight with a few other server-side controls, and the layout is the most flexible, but it is ultimately a service-side control in the performance of the loss, for high performance requirements of the site, even it is not allowed to use, The common practice of developers is to generate HTML code on the server and then output it to the client one at a time, so that the performance is improved but it's a headache to think of a whole bunch of HTML code on the service side. And now with the jtemplate problem can be a perfect solution, the server only need to serialize the object collection into JSON format and incoming client, the client then the JSON object to populate the template list, so that the service side of the transmission is only a JSON-formatted string, the amount of data transferred is greatly reduced, The work of the two traversal bindings is transferred to the client, which greatly reduces the pressure on the service side.

It says its benefits, let's talk about how to use it, or take a list of data for example.

1. To use Jtemplate, first introduce two JS script files:

<script type= "Text/javascript" src= "Scripts/jquery.js" ></script>
<script type= "Text/javascript" src= "Scripts/jquery-jtemplates.js" ></script>

It is important to note that Jtemplate is implemented on the basis of jquery, so the order in which the scripts are introduced cannot be reversed, otherwise it will be an error.

These scripts can be downloaded to http://jtemplates.tpython.com/.

2. Then build the template:

<!--results Container--
<div id= "Result_container" ></div>

<!--template Content--
<textarea id= "Template-items" style= "Display:none" >

<table border= "1" style= "Border-collapse:collapse" >

<tr><th> name </th><th> mailbox </th><th> Birthday </th></tr>
{#foreach $T as item}
<tr>
<td>{$T .item.name}</td>
<td>{$T .item.mail}</td>
<td>{$T .item.birthday}</td>
</tr>
{#/for}
</table>
</textarea>

This is the format of the jtemplate template, the template content is placed in the textarea, and the keyword and data are wrapped in curly braces, and to $t to represent data, keywords with # as the start tag.

3. Populate the template with JSON data and show

<script type= "Text/javascript" >
var data = [{name: ' Anne ', Birthday: ' 2001-01-01 ', Mail: '[email protected]‘ },
{name: ' Amelie ', Birthday: ' 2002-02-02 ', Mail: '[email protected]‘ },
{name: ' Polly ', Birthday: ' 2003-03-03 ', Mail: '[email protected]‘ },
{name: ' Alice ', Birthday: ' 2004-04-04 ', Mail: '[email protected]‘ },
{name: ' Martha ', Birthday: ' 2005-05-05 ', Mail: '[email protected]‘}]
Set up templates
$ ("#result_container"). Settemplateelement ("Template-items");

Populate the data and show
$ ("#result_container"). ProcessTemplate (data);

This can also be written as $ ("#result_container"). Settemplateelement ("Template-items"). ProcessTemplate (data);
</script>

When this is done, a list of data is presented:

5. Calling JavaScript in the template

In {} You are free to write JavaScript scripts, such as birthdays I want to display in a different format, shown as 2001/01/01, then we can change the template {$T. Item.birthday} to {$T. Item.birthday.replace (/- /g, '/')}, and then refresh the effect as follows:

Of course, it can also be packaged as a method to invoke, such as the first definition of JS method:

function FormatDate (date) {
Return Date.replace (/-/g, '/');
}

Then change the template to {formatdate ($T. Item.birthday)} to achieve the same effect.

6. How to include the textarea input box in the template

Jtemplate template content is placed in the textarea inside, but sometimes we want to include textarea in the template, there are two ways to achieve:

1) The contents of the annotation template, such as the template changed to:

<!--template Content--
<textarea id= "Template-items" style= "Display:none" >
<!--
<table border= "1" style= "Border-collapse:collapse" >
<tr><th> name </th><th> mailbox </th><th> Birthday &LT;/TH&GT;&LT;TH&GT;&LT;/TH&GT;&LT;/TR >
{#foreach $T as item}
<tr>
<td>{$T .item.name}</td>
<td>{$T .item.mail}</td>
<td>{$T .item.birthday}</td>
<td><textarea rows= "2" cols= "ten" ></textarea></td>
</tr>
{#/for}
</table>
-
</textarea>

The effects under IE are as follows:

But in other browsers (I have tested the browser 360, Google, Firefox) is not shown.

2) Remove the annotations and use the encoding of the special symbols to represent the special tags in the included textarea

such as the <textarea rows= "2" cols= "ten" ></textarea> replaced with &lt;textarea rows= "2" cols= "ten" &gt; &lt;/textarea&gt;

So that these mainstream browsers will be able to display the normal.

Jemplate supports encodings greater than > and less than <, but does not support the encoding of curly braces {}, such as the use of the My97datepicker date control in a template.

<input id= "D11" type= "text" onclick= "Wdatepicker ({el: $DP. $ (' D12 ')})"/>

Its argument is that a JSON object is curly braces, if it is directly put into the template can not get the desired effect, but there is also a workaround, such as the onclick event to write outside the template

7. The above example is how to use jtemplate binding a simple data list, but in fact jtemplate can bind any JSON object, and there are many ways to use, you can http://jtemplates.tpython.com/to understand

---------------------------------------------------------------------------------------

Templates is the JavaScript template engine, based on the jquery plugin. Official website: http://jtemplates.tpython.com/

Data preparation:

var data ={totalcount:64,lists:[{id: ' 2001 ', title: ' News One ', CreateDate: ' 2011-08-08 '},{id: ' 2002 ', title: ' News 22 ', CreateDate: ' 2011-08-08 '},{id: ' 2003 ', title: ' News ', CreateDate: ' 2011-08-08 '},{id: ' 2004 ', Title: ' News ', CreateDate: ' 2011-08-08 '},{id: ' 2005 ', Title: ' News ', CreateDate: ' 2011-08-08 '},]}

1, the introduction of library files

<script type= "Text/javascript" src= "jquery.js" ></script><script type= "Text/javascript" src= " Jquery-jtemplates.js "></script>

2. Writing a template
<div id= "Result" ></div><div id= "TemplateContainer" style= "Display:none;" ><table><tr><td>Id</td><td> title </td><td> release Time </td></tr>{ #foreach $T. Table as row}<tr><td>{$T. row.id}</td><td>{$T. row.title}</td><td>{ $T .row.createdate}</td></tr>{#/for}</table></div>
Syntax:  1. curly braces {..}, in which you can write any JavaScript code, such as {$T. toUpperCase ()} 2, {$T}: Represents data, such as the example above, $T. Table represents the Table object that gets data, $T. TotalCount is 64. 3. {#foreach}: Loop to get the data, as above: {#foreach $T. Table as row} {$T. row.title} {/for} Extended Syntax:   {#if}   Example:
{#if $T = = "true"} Good {#else} fail {#/if}
{#if $T. list_id = = 3} System List {#elseif $T. list_id = = 4} The Users list {#elseif $T. list_id = 5} Errors list {#/if}
  {#foreach}
{#foreach | var| As |name| [begin=| Code|] [count=| Code|] [step=| Code|]}.. {#else}: {#/for}
  Example:A, output all data:
{#foreach $T. Table as row}      {$T. Row.title}      {/for}   

b, start the output from the second record:
{#foreach $T. Table as row begin=1}      {$T. Row.title}      {/for}   

C, starting from the second and taking only 2 articles
{#foreach $T. Table as row Begin=1 count=2}      {$T. Row.title}      {/for}   

D. Using step
{#foreach $T. Table as row step=2}      {$T. Row.title}      
E, use Else

{#foreach $T. Table as row step=2}      {$T. Row.title}  {#else}   No record   

{#for}

Example:

{#for index = 1 to 10} {$T. Index} {#/for}
{#for index = 1 to Step=3} {$T. Index} {#/for}


3. Render the template and show

There are several ways to set up a template: A. Settemplateelement:parameter is an element ID in the page as in the example above B. SetTemplate:The parameters are specific to the template content, such as: $ ("#result"). SetTemplate ("template by {$T. Bold ()} version <em>{$Q. Version}</em>."); C.settemplateurl:Use external standalone template file URLs as parameters such as: $ ("#result"). Settemplateurl ("Example_multitemplate1.tpl"); 4. Operation Result: Complete code

Jtemplate is the JavaScript front-end HTML template engine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.