Getting started with JavaScript templates

Source: Internet
Author: User

For example, when using ajax to insert a li in a list, I directly splice the data with the html tag into a complete html and insert it into ul. No matter whether the data is retrieved from the server or from the user's input-either method is the same.
This splicing process is put in a JavaScript file, which is not elegant. If you also put the style in JavaScript, the data, structure, and style are all porridge. To maintain such code, you may want to commit suicide. The most out-of-the-box way is to put all the HTML to be generated on the page directly on the server side, and the ajax spit data contains the <li> tag. Such a page has almost no scalability, modifying a foreground style involves modifying the background code.

Later we learned that we should not customize DOM styles in JavaScript, but just define the corresponding class in the CSS file and use this class in JavaScript.

Next, we need to use a JavaScript template to separate the HTML structure (in this case, the <li> tag) from JavaScript.

There are many JavaScript templates on the market. Take handlebars as an example:

We define a template in the html of the page:Copy codeThe Code is as follows: <script id = "list-template" type = "text/x-handlebars-template">
<Li >{{ title }}</li>
</Script>

Then we can splice the data in our logic JavaScript code into this template:Copy codeThe Code is as follows: var source = $ ("# list-template" ).html (); // template source, which is generally placed in the html script. Here we use jQuery, you can also use other methods to directly obtain the content string.
Var template = Handlerbars. compile (source); // compile and generate a template
Var context = {title: "This is a todo item"} // obtain data. Data is generally obtained from ajax or input.
Var html = template (context); // data + template = new html

This is the basic usage, more logic can refer to the official documentation: http://handlebarsjs.com/

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.