Build your own JavaScript template small engine

Source: Internet
Author: User

Sometimes we don't need a very powerful JavaScript template engine (such as jquery Tmpl or HANDLEBARSJS), we just need to bind some very simple fields in a simple template, this article will use very simple techniques to help you achieve this small function.

First we define the template we need, in the script block with the ID template:

<!DOCTYPE HTML><HTML><Head>   <MetaCharSet=utf-8>   <title>Simple templating</title></Head><Body>   <Divclass= "Result"></Div>   <Scripttype= "template"ID= "template">    <H2>      <a href="{{href}}">{{title}}</a></h2><img SRC="{{IMGSRC}}"alt="{{title}}">  </Script> </Body></HTML>

Then we need to get the data we need through Ajax and other ways, and here we use our own defined arrays for ease of display:

 var  data = [{title: "Knockout Application Development Guide", href: "http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.html", img SRC: "Http://images.cnblogs.com/cnblogs_com/TomXu/339203/o_knockout2.jpg"}, {title: "Microsoft ASP. NET Site Deployment Guide", H Ref: "Http://www.cnblogs.com/TomXu/archive/2011/11/25/2263050.html", Imgsrc: "Http://images.cnblogs.com/cnblogs_ Com/tomxu/339203/o_vs.jpg "}, {title:" HTML5 Study Notes Concise Edition ", href:" Http://www.cnblogs.com/TomXu/archive/2011/12 /06/2277499.html ", imgsrc:" Http://images.cnblogs.com/cnblogs_com/TomXu/339203/o_LearningHtml5.png "}], 


We have 2 ways to bind this data to the template, the first is a very simple hardcode method, and the second is to automatically identify the variable type.

Let's first look at the first way, by replacing the value in the curly braces with the value in data to achieve the goal:

 for (; i < Len; i++) {    fragment + = Template      . replace (/\{\{title\}\}/, Data[i].title)      . Replace (/\{\{href\}\}/, Data[i].href)      . Replace (/\{\{imgsrc\}\}/, DATA[I].IMGSRC);} result.innerhtml = fragment;

Operating effect: http://jsfiddle.net/TomXu/3GKw2/


The second approach is more flexible, replacing all curly braces with regular expressions instead of a replacement, which is relatively flexible, but be aware of the fact that the template label may not exist in the data:

Template = Document.queryselector (' #template '). Innerhtml,result = Document.queryselector ('. Result '), Attachtemplatetodata;//using the template and data as parameters, the values are replaced by all the items in the data on the label of the template (note that it is not possible to traverse the template label because the label may not exist in the data). Attachtemplatetodata =function(Template, data) {vari = 0, Len = data.length, fragment = ";//iterate through each item in the data set and replace it accordingly.        functionReplace (obj) {varT, key, Reg;//Traverse all properties under the data item, look for the label as the key value, and replace             for(Keyinchobj) {reg =NewRegExp (' {' + ' + key + '} ', ' IG ');            t = (T | | template). replace (Reg, Obj[key]); }returnT } for(; i < Len; i++)        {Fragment + = replace (data[i]); }returnFragment }; result.innerhtml = Attachtemplatetodata (template, data);

Operating effect: http://jsfiddle.net/TomXu/HjSLf/

This allows us to define our own labels and item attributes without having to modify the JS code.

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

Build your own JavaScript template small 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.