[Go] jquery author John resig The Micro-template engine written by: JavaScript micro-templating

Source: Internet
Author: User

I ' ve had a little utility that I've been kicking around for some time now the I ' ve found to being quite useful in my JAVASCR IPT application-building endeavors. It's a super-simple templating function that's fast, caches quickly, and is easy-to-use. I have the a couple tricks that I use for make it real fun to mess with.

Here's the source code to the templating function (a more-refined version of this code would in my upcoming book Secrets of the JavaScript Ninja):

//Simple JavaScript Templating//John resig-http://ejohn.org/-MIT Licensed(function(){  varCache = {};  This. Tmpl =functionTmpl (str, data) {//Figure out if we ' re getting a template, or if we need to    //load the Template-and is sure to cache the result.    varfn =!/\w/.test (str)?Cache[str]= Cache[str] | |Tmpl (document.getElementById (str). InnerHTML)://Generate A reusable function that would serve as a template      //generator (and which'll be cached).      NewFunction ("obj",        "Var p=[],print=function () {p.push.apply (p,arguments);};" +//introduce the data as local variables using with () {}"With (obj) {P.push ('" +//Convert the template into pure JavaScriptstr. replace (/[\r\t\n]/g, ""). Split ("<%"). Join ("\ T"). Replace (/((^|%>) [^\t]*] '/g, ' $1\r '). Replace (/\t= (. *?) %>/g, "', $, '"). Split ("\ T"). Join ("');"). Split ("%>"). Join ("P.push ('"). Split ("\ r"). Join ("\ \"))      + "');} Return P.join (");); //provide some basic currying to the user    returnData?fn (data): FN; };}) ();

You would use it against templates written "This" (it doesn ' t has the to IS in this particular manner-but it ' s a style t Hat I enjoy):

<Scripttype= "text/html"ID= "Item_tmpl">  <Div ID="<%=id%>"class="<%= (i% 2 = = 1? )"even" : "")%>">    <Div class="Grid_1 Alpha Right">      <img Class="righted"src="<%=profile_image_url%>"/>    </div>    <Div class="Grid_6 Omega Contents">      <P><b><a href="/<%=from_user%>"><%=From_user%></a>:</b> <%=text%></p>    </div>  </div></Script>

You can also inline script:

<Scripttype= "text/html"ID= "User_tmpl">  <%  for ( varI= 0; I<users.length; I++ ) { %>    <Li><a href="<%=users[i].url%>"><%=Users[i].name%></a></Li>  <% } %></Script>

Quick tip:embedding scripts in your page that has a unknown content-type (such is the case here-the browser doesn ' t kn ow how to execute a text/html script) is simply ignored by the Browser-and by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into your page. I like to use this technique for quick-and-dirty cases where I just need a little template or both on the page and want SOM Ething Light and fast.

And you would use it from script like so:

var results = document.getElementById ("results"= Tmpl ("Item_tmpl", dataObject);

You could pre-compile the results for later use. If the templating function with only an ID (or a template code) then it ' ll return a pre-compiled function that yo U can execute later:

 var  show_user = Tmpl ("Item_tmpl"), html = " ; for  (var  i = 0; i < users.length; I++) {html  += Show_user (Users[i]);}  

The biggest falling-down of the method, at this point, are the parsing/conversion code-it could probably use a little lov E. It does use one technique that I enjoy, though:if "re searching and replacing through a string with a static search And a static replace it ' s faster to perform the action with .split("match").join("replace") -which seems counter-intuitive but it manages to work That's the most modern browsers. (There is changes going in place to grossly improve the performance of the .replace(/match/g, "replace") next version of Firefox-so the Prev IOUs statement won ' t is the case for long.)

Feel free to has fun with It-i ' d is very curious to see what mutations occur with the script. Since It's so simple it seems like there's a lot that can still is done with it.

Original address: http://ejohn.org/blog/javascript-micro-templating/

[Goto] jquery author John Resig, a micro-template engine written by: JavaScript micro-templating

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.