How to use templates to extract HTML from JavaScript _javascript tips

Source: Internet
Author: User
Tags html tags script tag sprintf

First, when you need to inject a large section of HTML tags to the page, you should use server rendering (HTML tags from the server loading)

This method places the template on the server using the XMLHttpRequest object to get the external label (for example, multi-page applications)

function Loaddialog (name, oncomplete) {
 var xhr = new XMLHttpRequest ();
 Xhr.open (' Get ', '/js/dialog/' +name, true);
 Xhr.onreadystatechange = function () {
  if (xhr.readystate = = 4 && xhr.status =) {
   var div = document.ge Telementbyid (' Dlg-holder ');
   div.innerhtml = Xhr.responsetext;
   OnComplete ();
  } else {
   //Error handling code
  }
 };
 Xhr.send (null);
}
Use Yui's API
function Loaddialog (name, oncomplete) {
 y.one (' #dlg-holder '). log ('/js/dialog/' +name, OnComplete);
}
API
function Loaddialog (name, OnComplete) {
 $ (' #dlg-holder ') using jquery. Load ('/js/dialog/' +name, OnComplete);
}

Second, the client template
for a small number of label segments, you should consider using a client template.
Client templates are tagged fragments with ' slots ' (placeholders) that are replaced with data by JavaScript programs (template engines), and then inserted into the page by the replacement label fragment.

JavaScript program (template engine)
Custom Template text handlers

function sprintf (text) {
 var i=1,args=arguments;
 Return Text.replace (/%s/g, function () {return
  (i<args.length)? args[i++]: ';
 } ';
}

Template Text Storage location
1. stored in HTML comments

<ul id = ' mylist ' ><!--<li id= ' item%s ' ><a href= '%s ' >%s</a></li>-->
 ...
</ul>

Because the annotation is also a DOM node, it can be extracted through JS:

Methods that format and insert the DOM define
function AddItem (url,text) {
 var mylist = document.getElementById (' mylist ');
 var templatetext = Mylist.firstChild.nodeValue; Extract template text
 var result = sprintf (templatetext,url,text);
 div.innerhtml = result;
 mylist.insertadjacenthtml (' beforeend ', result);
}
Call method
AddItem ('/item/4 ', ' ' a ');
AddItem ('/item/4 ', ' Second item ');

2. Inside the script tag that is stored in the custom type attribute

<script type= ' text/x-my-template ' id= ' List-item ' >
 <li><a '%s ' >%s</a></li>
</script>
function AddItem (url,text) {
 var mylist = document.getElementById (' mylist ');
 var script = document.getElementById (' List-item ');
 var templatetext = Script.text; Extract template text
 var result = sprintf (templatetext,url,text);
 var div = document.createelement (' div ');
 div.innerhtml = Result.replace (/^\s*/, "); Removes leading spaces from the template text (because it is the next line in the <script> label)
 Mylist.appendchild (div.firstchild);
}

Use third party template systems (e.g.: artTemplate-3.0, Jade, handlebars, dot.js)

Take handlebars as an example:

Handlebars recommends that templates be stored in a script tag

<script type= ' text/x-handlebars-template ' id= ' List-item ' >
 {{#if items}}
 <ul id= ' mylist ' >
  { {#each Items}}
   <li><a href= ' {{URL}} ' >{{text}}</a></li>
  {/each}}
 </ul>
 {{/if}
}} </script>
funtion AddItem (url,text) {
 var mylist = document.getElementById (' mylist '),
   script = document.getElementById (' List-item '),
   template = Handlebars.compile (Script.text),//Extract template text, return formatted method
   div = Document.createelement (' div '), result
   ;

 result = Template ({text:text,url:url});
 div.innerhtml = result;
 Mylist.appendchild (Div.firstchild);
}
Call
AddItem ('/item/4, ' ' a ');

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.