4 line Code Implementation JS template engine

Source: Internet
Author: User

In peacetime coding, often to do the work of splicing strings, such as JSON data with HTML display, the past string concatenation and logic mixed together will make the code obscure, increase the cost of collaboration and maintenance of many people. And the use of the front-end template mechanism can be a good solution to this problem.

The Subtle Tmpl

The front-End template class is open source, but most of the JQuery author John Resig developed the "JavaScript Micro templating" the most subtle, a few strokes to achieve the core function of the template engine. Its introduction and use of the way to see the author blog: http://ejohn.org/blog/javascript-micro-templating/

Perfectly formed, in addition to the basic data attached, also has a caching mechanism, logic support. Now, if I were to list a JavaScript's most energy-efficient custom function rank, the first name would be the $ function (document.getElementById), and the second place would be tmpl.

Of course, it's not perfect, and I found some problems using the process:

Tmpl Ointment

The escape character cannot be handled correctly, such as: Tmpl (' <%=name%>\\<%=id%> ', {name: ' sugar cake ', id: ' 1987 '}); it will error. If working properly, it should output: Sugar cake \1987

The single quotation mark in the data is not recognized

The default value of the set variable is complex, such as

Tmpl (' <%if (obj.name) {%><%=name%><%}else{%> default <%}%> ', {name: ' Sugar Cake '}); Set name defaults to "Default value"

Tmpl optimized version

Don't say much nonsense, first to the code:

1 functionTmpl (str, data) {2     var$ = ' $ ' + (+NewDate)3, fn =function(data) {4         varI, variable = [$], value = [[]];5          for(Iinchdata) {6 Variable.push (i);7 Value.push (Data[i]);8         }9         return(NewFunction (variable, fn.$))Ten. Apply (data, value). Join (""); One     }; A  -     //parsing a template into a function -fn.$ = fn.$ | | $ + ". Push ('" the+ str.replace (/\\/g, "\\\\") -. replace (/'/g, ' \ \ ')//prevent single parenthesis errors -. replace (/[\r\t\n]/g, "") -. Split ("[:"). Join ("\ T") +. Replace (/((^|:]) [^\t]*] '/g, ' $1\r ') -. replace (/\t= ([^\?] *?):]/g, "', $, '") +. replace (/\t= ([^\?] *?) \? (. *?):]/g, "', this.$1| | ' $ ', ' ")//[: =data?:] [: =data? Any content:] A. split ("\ T"). Join ("');") at. Split (":]"). Join ($ + ". Push ('") -. Split ("\ r"). Join ("\ \" ") -+ "'); return" + $; -  -     //If no data is defined, the compiled function is returned, and the data is passed directly to the application . -     //eliminate the time of every parse into a function in     returnData?fn (data): FN; -  to};

Well, the above code looks more than 4 lines, forgive me the title party. However, this code is compressed, it is really only four lines ^_^. Let's try to deconstruct it in detail below.

First look at the use example:

1 //Loop Structure2 3 varTPL = ' [: for (var. k in Ary) {var one=ary[k];:] '4+ ' <p>[:=one:]</p> '5+ ' [:}:] ';6 vardata = {ary:[123, ' abc ']};8 vardiv =Tmpl (tpl,data);TenConsole.log (DIV);//</p>123</p><p>abc</p> One  A  - //Variable Validation -  the varTPL = ' [: if (this.name!==undefined) {:] '//Note that you must use THIS.name, use name directly, and error if undefined -+ ' <p>[:=name:]</p> ' -+ ' [:}:] '; - vardata = {name: ' abc '}; - vardiv =Tmpl (tpl,data); A 
at //you can also use undefined variables in such a convenient way: -
- varTPL = ' <p>name:[:=name?:], Name:[:=name? Default value:]</p> '; - vardata = {No: ' abc '}; - vardiv =Tmpl (tpl,data); - inConsole.log (DIV);//<p>name:, Name: Default value </p> - to + //Cache Compilation Results - the * varTPL = ' [: for (var. k in Ary) {var one=ary[k];:] ' $+ ' <p>[:=one:]</p> 'Panax Notoginseng+ ' [:}:] '; - vardata = {ary:[123, ' abc ']}; + varRender = Tmpl (TPL);//generates a cache without passing in data, saving a large number of regular operations using the cache multiple times the vardiv = render (data);//incoming data, substituting variables, parsing into the final result + -Console.log (DIV);//<p>123</p><p>abc</p>

How to use: Use any JS code between [: and:] and output the variable as a string through [: =data:]. For more detailed usage/manuals, please see: Http://docs.codekart.jojoin.com/p/tool_tmpl

Optimization of the Place:

One. Correctly handle escape characters such as escape characters \ '

Two. Change the package character <%%> to [::] To prevent conflicts with the HTML tag </> and the remainder operator%.

Three. Modify the environment variable obj to this

Tmpl (' <%if (obj.name== "name")%> ')//old version

Tmpl (' [: if (this.name== ' name '):] ')//new version

Four. Add a default value to a variable

Tmpl (' <%if (obj.name) {%><%=name%><%}else{%> default <%}%> ')//old version

Tmpl (' [: =name? Default value:] ')//new version

Five. Remove the WITH statement to significantly improve engine performance

Six. Remove the optional features and keep it streamlined

Seven. Add debug mode

Print Template compilation Intermediate results:

Console (Tmpl (' <p>[:=name:]</p> '). $);

$1408707567855.push (' <p> ', name, ' </p> '); return $1408707567855

This engine function is broadly divided into two parts:

I. Top half: template function parsing execution

Two. Lower half: Regular operations generate template functions

As can be seen, the focus of the engine implementation is mainly in the lower part of a bunch of regular expressions, that is, "template compilation" process. Here I'm not going to make every regular function clear, that's too big (well I'm lazy), you crossing please read the study yourself.

In addition, this template engine has been integrated into the node. JS Web Development Framework Codekart.

Codekart is a set of application development frameworks and toolkits for use by node. JS developers. It provides a rich set of standard libraries and simple interfaces and logical structures to enable developers to develop projects faster. Using Codekart can reduce the amount of code written and devote your energies to the creative development of your project.

It has done the following things well for you:

Elegant frame of mind

If you need a real framework, rather than a module/middleware/toolbox, if you need simplicity and convenience and need a clear, natural sense of comfort, then Codekart will be the best choice.

High-Performance HTTP server

The performance of the Codekart processing HTTP requests is close to the native node. js code: Http.createserver (), because the framework simply encapsulates this function, and its performance loss is only a URL regular matching operation, routing request handlers.

A convenient static file server

Put the file into the static/directory, start Codekart,url access, done!

Web page modularity Support

In fact, this is the best part of Codekart! It is a front-end integration, can be like writing a configuration file as a Web page, the framework automatically complete JS, CSS, TPL file modular loading, merging, compression, and in HTML reference, automatic parsing of HTML templates, and Support page inheritance and polymorphism, everything is so simple and easy!

A rich toolbox

Codekart prepared a series of powerful front-end tool sets, involving process communication, data caching, file reading, file uploading, data acquisition and processing, Process Control, task planning and many other aspects.

Framework source Hosting in Github:https://github.com/yangjiepro/codekart Welcome to submit new Code!

4 line Code Implementation JS template 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.