JavaScript input mailbox Auto Prompt instance code _javascript tips

Source: Internet
Author: User

Originally want to arttemplate source analysis of the comments put up to share, but after a year, can not find, had to analyze the template engine principles, their own try

Write down the template engine to share with you, leave a souvenir, remember also compared to several template engine.

Here is the JS template engine, with the native JavaScript syntax, so very similar to PHP's native template engine.

What is the role of the front-end template engine?

1. Can make front-end development simpler, do not need to generate a DOM structure and use the + operator to stitching strings, and only need an element (inside the HTML template), or a variable (stored template), or a template file

2. Easy to maintain, reduce coupling, if your DOM structure changes, do not need to change the logical code, but only need to change the corresponding template (file)

3. Can be cached, if your template is a similar. tpl file, then completely can be loaded with the browser, and still save. Speaking of. TPL files, you can do more than just caching, you can also do through the module loader

Will. TPL as a module, so you can load files on demand, not more bandwidth, faster page speed?

4. Wait, wait.

What is the principle of the front-end template engine?

The principle is very simple is the object (data) + template (containing variables)-> string (HTML)

How is the front-end template engine implemented?

By parsing the template, converting the template to a function according to the lexical, and then by calling the function and passing the object (data), the output string (HTML)

(Of course, the specific also depends on the code)

Just like this:

Copy Code code as follows:

var TPL = ' I am <%= name%>, <%= age=> years old '; <%=xxx>% lexical, marked as variable

var obj = {
Name: ' Lovesueee ',
Age:24
};
var fn = Engine.compile (TPL); Compiling into functions

var str = fn (obj); Render a String

Example:

Copy Code code as follows:

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>ice demo</title>
<script src= "/javascripts/jquery/jquery-1.7.2.js" ></script>
<script src= "/javascripts/ice/ice.js" ></script>
<body>
<div id= "Content" ></div>
</body>

<script type= "text/html" id= "TPL" >
<div>here is the render result:</div>
<% = This.title ();%>
<table border=1>
<% for (var i=0,tl = this.trs.length,tr;i<tl;i++) {%>
<%
TR = this.trs[i];
if (Tr.sex = = "female") {
%>
<tr>
<td><%= tr.name;; %></td> <td><%= Tr.age; %></td> <td><%= Tr.sex | | "Male"%></td>
</tr>
<%}%>
<%}%>
</table>

<%= this.include (' tpl2 ', this); %>
</script>
<script type= "text/html" id= "TPL2" >
<div>here is the render result:</div>
<% = This.print (' Welcome to Ice Template ');%>
<table border=1>
<% for (var i=0,tl = this.trs.length,tr;i<tl;i++) {%>
<%
TR = this.trs[i];
if (Tr.sex = = "Male") {
%>
<tr>
<td><%= tr.name;; %></td> <td><%= Tr.age; %></td> <td><%= Tr.sex | | "Male"%></td>
</tr>
<%}%>
<%}%>
</table>

</script>
<script>
    var trs = [
         {name: "Stealth Killer", Age:29,sex: "Man"},
        {name: "Sola", Age:22,sex: "Man"},
        {name: "Fesyo", Age:23,sex: "Female"},
         {name: "Love Demon Pot", Age:18,sex: "Man"},
        {name: "Ryu Qi", Age:25,sex: "Male "},
        {name:" You do not understand ", Age:30,sex:" Female "}
   ]

   //var html = Ice ("TPL", {
   //     trs:trs,
 & nbsp; //     href: "yun_qi_img/type4.jpg"
   //},{
    //     title:function () {
   //          return "<p> This is a snippet of code using view helper Output </p>"
   //    }
   //});
    var elem = document.getElementById (' TPL ');
    var tpl = elem.innerhtml;

var html = Ice (tpl,{
Trs:trs,
HREF: "Yun_qi_img/type4.jpg"
},{
Title:function () {
Return <p> This is a code fragment that uses the View helper output </p> "
}
});
Console.log (HTML);
$ ("#content"). HTML (HTML);

</script>


Simple to implement:

Copy Code code as follows:

(function (Win) {

Template Engine Routing functions
var ice = function (ID, content) {
Return ice[
typeof content = = = ' object '? ' Render ': ' Compile '
].apply (ice, arguments);
};


ice.version = ' 1.0.0 ';

Template configuration
var iconfig = {
Opentag: ' <% ',
Closetag: '%> '
};


var isnewengine =!! String.prototype.trim;

Template caching
var Icache = Ice.cache = {};

Auxiliary functions
var ihelper = {
Include:function (ID, data) {
return Irender (ID, data);
},
Print:function (str) {
return str;
}
};

Prototype inheritance
var iextend = Object.create | | Function (object) {
function Fn () {};
Fn.prototype = object;
return new Fn;
};

Template compilation
var icompile = Ice.compile = function (ID, TPL, options) {

var cache = null;

ID && (cache = Icache[id]);

if (cache) {
return cache;
}

[ID | tpl]
if (typeof TPL!== ' string ') {

var elem = document.getElementById (ID);

options = TPL;

if (elem) {
[ID, Options]
options = TPL;
TPL = Elem.value | | elem.innerhtml;

} else {
[TPL, Options]
TPL = ID;
id = null;
}
}

options = Options | | {};
var render = Iparse (TPL, Options);

ID && (Icache[id] = render);

return render;
};


Template rendering
var irender = Ice.render = function (ID, data, options) {

return Icompile (ID, Options) (data);
};


var Iforeach = Array.prototype.forEach?
function (arr, fn) {
Arr.foreach (FN)
} :
function (arr, fn) {
for (var i = 0; i < arr.length; i++) {
FN (Arr[i], I, arr)
}
};


Template parsing
var iparse = function (TPL, options) {

var html = [];

var js = [];

var Opentag = Options.opentag | | iconfig[' Opentag '];

var Closetag = Options.closetag | | iconfig[' Closetag '];

Depending on the browser to take a different concatenation string strategy
var replaces = Isnewengine
? ["Var out= ', line=1;", "out+=", ";", "out+=html[", "];", "This.result=out;"
: ["Var out=[],line=1;", "Out.push (", ");", "Out.push (html[", "]);", "This.result=out.join ("); ";

function body
var body = replaces[0];

Iforeach (Tpl.split (Opentag), function (val, i) {

if (!val) {
Return
}

var parts = val.split (Closetag);

var head = Parts[0];

var foot = parts[1];

var len = parts.length;
Html
if (len = = 1) {
Body + + Replaces[3] + html.length + replaces[4];
Html.push (head);

} else {

if (head) {
Code
Remove spaces
Head = Head
. replace (/^\s+|\s+$/g, "")
. replace (/[\n\r]+\s*/, "")


Output statement
if (head.indexof (' = ') = = 0) {
Head = head.substring (1). replace (/^[\s]+|[ \s;] +$/g, "");

BODY = + Replaces[1] + head + replaces[2];
} else {
BODY = = Head;
}

BODY = = ' line+=1; ';
Js.push (head);
}
Html
if (foot) {
_foot = Foot.replace (/^[\n\r]+\s*/g, ");
if (!_foot) {
Return
}
Body + + Replaces[3] + html.length + replaces[4];
Html.push (foot);
}
}
});

BODY = "var render=function (data) {Ice.mix (this, data); try{"
+ Body
+ replaces[5]
+ "}catch (e) {ice.log (' rend error: ', line, ' line '); Ice.log (' Invalid statement: ', js[line-1]); throw e;};"
+ "var proto=render.prototype=iextend (ihelper);"
+ "Ice.mix (proto, Options);"
+ "return function (data) {return new Render (data).";

var render = new Function (' HTML ', ' JS ', ' iextend ', ' ihelper ', ' options ', body);

return render (HTML, JS, Iextend, Ihelper, Options);
};

Ice.log = function () {
if (typeof console = = ' undefined ') {
Return
}

var args = Array.prototype.slice.call (arguments);

Console.log.apply && console.log.apply (console, args);

};

Merging objects
Ice.mix = function (target, source) {
for (var key in source) {
if (Source.hasownproperty (key)) {
Target[key] = Source[key];
}
}
};

Registration function
Ice.on = function (name, FN) {
Ihelper[name] = fn;
};

Clear Cache
Ice.clearcache = function () {
Icache = {};
};

Change Configuration
Ice.set = function (name, value) {
Iconfig[name] = value;
};

Exposure interface
if (typeof module!== ' undefined ' && module.exports) {
Module.exports = template;
} else {
Win.ice = ice;
}

}) (window);

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.