Mastering JS Template engine

Source: Internet
Author: User

To do a small project recently, whether it is the use of Angularjs or Reactjs, both feel overqualified. In fact, I may only need to introduce a jquery, but think of the operation of jquery on the DOM, for already accustomed to the two-way binding mode of me, it is not a pain.

Heard the words: "Technology is not absent, only late", many technologies themselves do not know, not without. Today I would like to introduce a simple JS template engine arttemplate, let us sail it ~

I. Overview

Arttemplate is a new generation of JavaScript template engines that use precompilation to make a qualitative leap in performance and take advantage of JavaScript engine features to make performance extremely good both in front-end and back-end.

Two, my pain point

Let's take a look at a piece of code, and when I use Ajax to get a bunch of JSON data in the background, I might do this when I populate the page:

123456789101112 $.ajax ({type:' GET ',Url:'/server/list.json ',Successfunction (data) { var lists = '; For (var i=0;i<data.content.rows.length;i++) { Lists + =' <li><div class= ' lititle ' > ' +data.content.rows[i].leaverulename+' (Total ' +data.content.rows[i '). durationstr+') </div><div class= "Timer" ><span> start time: ' +data.content.rows[i].starttime+' </span><span> end time: ' +data.content.rows[i].endtime+' </span></div><div class= "Btns" ><p><a href= "#" class= "button Button-round Blue" > ' +data.content.rows[i].customapprovalstatus+' </a></p></div><div class= "Info" > Just applied </div></li> '; } $(' #myList '). Append (lists);}, Error:function (xhr, type) {//omitted here} })

HTML code:

1 <ul class="List-container" id="myList" ></ul>

This piece of code may not be a problem with functionality. But let's look at the lists variable, where the information has exploded, the HTML structure and data fills, and I don't want to maintain it.

It was the sentence: "At this time I wrote the code, only me and God knows." Half a month later, I am afraid that only heaven knows! ”

Third, the treatment of pain points

It's not just a nightmare, it's digging a hole in a mine??。 Well, no longer sentimental, we change arttemplate to try, the code may be this:

Note: Remember to introduce template.js in advance Oh ~

12345678 $.ajax ({type: ' GET ', URL: '/server/list.json ', success: function (data) { $ (' # MyList '). Append (Template (' Mylisttpl ', {lists:data.content.rows})); }, Error: function (xhr, type) {//omitted here}})

HTML code:

12345678910111213141516 <script type="text/html" id="Mylisttpl" > {Each lists}}<li data-id="{{$value. id}}" > <div class="Lititle" >{{$value. Overtimerulename}} (Total {{$value. durationstr}})</ div> <div class="Timer" > <span> start time: {{$value. startTime}}</span> <span> End time: {{$value. endTime}}</span> </div> <div class="Btns" > <p><a href="#" class= "button button-round {{! $value. isensure? ' Blue ':($value. iseffective? ' Green ': ' Red ')} ' >{{! $value. isensure? ' Pending confirmation ':($value. iseffective? ' Confirmed ': ' Expired ')}}</a></p> </div> <div class="info" >{{$value. Applytime | timeformat}} request </div> </li> {{/each}}</script> <ul class="List-container" id="myList" ></ul>

Note: The type= "text/html" in script

This code is very clear, we set up the MYLISTTPL as a template, the inside of the HTML structure is clear, the variables are wrapped in the double curly braces. So what's the value in lists, you might see this in detail:

1 $ (' #myList '). Append (Template (' Mylisttpl ', {lists:data.content.rows}));

Yes, we use templates to precompile the template and plug the data into the lists. In this way, JS does not need very complex logic, HTML also preserves the original structure.

~ Buzz ~ Buzz, well, the whole world is quiet!

Iv. Examples of usage

Arttemplate is very simple to use, let's illustrate each of them:

1.template (Id,data), passing data to the ID template.

12345678 <script id="test" type="text/html" > <H1>{{title}}</h1> <ul> {Each list as value I}} <li> Index {{i + 1}}: {{value}}</li> {{/each}} </ul> </script>

JS Code:

123456 var data = { title: ' label ', list: [' literary ', ' blog ', ' photography ', ' movie ', ' ballad ', ' travel ', ' guitar '] }; var html = template (' test ', data); document.getElementById (' content '). InnerHTML = html;

2.template.compile (source,options), pre-compiling template data.

1234567891011121314 <script>var Source = ' <ul> '+ ' {Each list as value I} '+ ' <li> Index {{i + 1} }:{{value}}</li> '+ ' {{/each}} '+ ' </ul> '; var render = Template.compile (source); var html = render ({ list: [' photography ', ' movie ', ' ballad ', ' travel ', ' guitar ')} ); document.getElementById (' content '). InnerHTML = html; </script>

The above two ways, is a simple data rendering, the actual application we may encounter more complex operations, described below.

3.template.helper (Name,callback), use the custom method in the template.
In some cases, we need to preprocess the data, like the filter operation in Angularjs, what do we do?

123 <script id="test" type="text/html" > {{time | timeformat}} </script>

1234 Template.helper (' timeformat ',function (date) { var result = Common.formatetime (date); return result;});

As shown above, we call the Template.helper method and put the custom method in the callback function, then the data is not ready to be processed. My scenario here is to format the time data, and I want him to show up as a "1 hours ago, just" copy.

4.template.config (name,value), change the default configuration of the engine.

5.include can embed a template.

123456789101112 <div id="Content" ></div> <script id="test" type="text/html" > <H1>{{title}}</h1> {{include ' list '}}</script> <script id="list" type="text/html" > <ul> {Each list as value I}}<li> Index {{i + 1}}: {{value}}</li> {{/each}}</ul> </script>

JS Code:

123456 var data = {title: ' embed sub-template ',list: [' literary ', ' blog ', ' photography ', ' movie ', ' ballad ', ' travel ', ' guitar '] }; var html = template (' test ', data); document.getElementById (' content '). InnerHTML = html;

The focus is on:

1 {{include ' list '}}

It is easy to include a template with ID list in it.

6. Escaping

12345 <div id="Content" ></div> <script id="test" type="text/html" > <p> Not escaped: {{#value}}</p> <p> Default escape: {{value}}</p> </script>

JS Code:

12345 var data = { value: ' <span style= ' color: #F00 ' >hello world!</span> '}; var html = template (' test ', data); document.getElementById (' content '). InnerHTML = html;

We only need to add the "#" number, the template is not escaped by default.

7. Print your data on the page.
Of course, you can also play this way:

123 <script id="test" type="text/html" > {{print a b c}} </script>

JS Code:

12345678 var html = '; var data = {A: ' hello ',B: '--world ',C: '--!!! '}; html = template (' test ', data); document.write (HTML);

Basic usage That's all, isn't it easy to think, then try it quickly!

Five, the principle analysis

Of course, we don't just stay on top of the hierarchy, how does the template engine work?

The arttemplate template compiler extracts all of the template variables according to some simple rules, which are declared on the head of the render function, which is similar to this function:

12345678910 var render = function ($data) {var content = $data. Content,$out = '; $out + = ' if (typeof content = = = ' string ') {$out + = content;} $out + = ' return $out;};

This auto-generated function is like a hand-written JavaScript function, with a significant reduction in CPU and memory usage, with near-limit performance.

It is worth mentioning: Arttemplate Many features are based on precompiled implementations, such as sandbox specifications and custom syntax.

Although each engine is implemented differently from template syntax, syntax parsing, variable assignment, and string concatenation, the key rendering principle is still the dynamic execution of JavaScript strings.

Well, donuts. If you want to know more, to download a template.js, look at the source bar.

Six, load test and commissioning


The rendering efficiency test under Chrome is 25, 32 times times that of the well-known engine mustache and micro Tmpl respectively.
In addition to the performance benefits, debugging features are also worth mentioning. The template debugger can pinpoint the template statements that throw rendering errors, solve the pain of not being debugged during the scripting process, make development more efficient, and avoid situations where a single template error causes the entire application to crash. Examples are as follows:

12345678 <script id="test" type="text/html" > <ul> {Each list}} {{/each}} {{Window.alert=null}} </ul> </script>

JS Code:

123 var html = '; html = template (' Test ', {}); document.write (HTML);

The list variable is not assigned, and the template engine throws the error, conveniently locating and troubleshooting.

Vii. Accidental Harvesting

Originally I thought arttemplate would be the fastest, and found the dot, very good, you have successfully aroused my attention.

As you can see, JS template engine A variety of, if each engine to write an article, I think I should not do other things in a few years (I would not be so boring?? )。 So, don't dwell on which template engine to use. Keep in mind that what is best for you.

Viii. Summary

According to learning ideas, from top to bottom with this article. I want to write a detailed article about the template engine, mainly to make up for the guilt in the heart. In fact, as early as 2014 I have heard of arttemplate, but only to stop at the level of hearing.

When the Earth people are in use, I have not started, when everyone has to chase the clouds of the horizon, I reacted.

Bloody lessons, I would like to dedicate to and I have the same experience and feelings of people, any time please do not stop learning footsteps, even if late, but at least you tried.

Mastering JS 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.