Front-end-"learning experience"-a simple way to render templates

Source: Internet
Author: User

Usually we use AJAX to request the completion of data after the process is often a rendering of data, at the beginning of my practice is to do a data template in the HTML interface, using some similar to the angular tag, and then use the Replace function to replace those marked as real data, Later, a more concise approach was found in the learning process. This method uses the method of capturing arrays in regular expressions, which is perfect for rendering data.

var regexp = /(?: \ {\{) ([a-za-z][^\s\}]+) (?:\} \})/g 
Function render (template, data)  {
     return  Template.replace (Regexp, function (fullmatch, capture)  {           if  (Data[capture])  {                return data[capture];           } else {                return fullMatch;           }      }); }
Window.rendertemplate = render;

The core code, like the one we define here, matches the data in {{}}, and the Render method passes two parameters, one is the template, the other is the data to be rendered, such as the DOM structure of the template we define as <TABLE><TR><TD >{{aa}}</td></tr></table>, the return data is JSON, also contains {AA: "real Value"}, then we call the end of Render (Template,data) After getting a template with real data, you can try it. If the project is small, try to write your own rendering template.

Front-end-"learning experience"-a simple way to render templates

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.