Enter the email address in JavaScript to automatically prompt the instance code.

Source: Internet
Author: User

I wanted to share my previous comments on artTemplate source code parsing. However, after a year, I couldn't find them. I had to try it myself after I analyzed the template engine principles.

The template engine I wrote was shared with you. I remember that I compared several template engines.

The js template engine mentioned here uses the native javascript syntax, so it is similar to the native template engine of php.

 

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

1. it makes front-end development easier. You do not need to use the + operator to splice strings to generate a dom structure, but only need one element (the html template in it ), or a variable (storing the template) or a template file

2. Easy to maintain and reduce coupling. If your dom structure changes, you do not need to change the logic code. Instead, you only need to change the corresponding template (file)

3. It can be cached. If your template is a file similar to. tpl, you can load it in a browser and save it. Speaking of the. tpl file, you can not only cache it, but also use the module loader.

If you use. tpl as a module, you can load files as needed. Isn't it easier to save bandwidth and speed up the page?

4. etc.

 

How does the front-end template engine work?

The principle is simple: Object (data) + template (containing variables)-> string (html)

 

How is the front-end template engine implemented?

Parse the template, convert the Template into a function based on the lexical structure, call the function, pass the object (data), and output the string (html)

(Of course, you should also look at the code)

Like this:

Copy codeThe Code is as follows:
Var tpl = 'I am <% = name %>, <% = age => years old'; // <% = xxx> % lexical, marked as a variable

Var obj = {
Name: 'lovesueee ',
Age: 24
};
Var fn = Engine. compile (tpl); // compile it into a function

Var str = fn (obj); // render the string

Example:

Copy codeThe Code is as follows:

<! Doctype html>
<Html>
<Head>
<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. 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> <% = tr. age; %> </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> <% = tr. age; %> </td> <% = tr. sex | "male" %> </td>
</Tr>
<% }%>
<% }%>
</Table>

</Script>
<Script>
Var trs = [
{Name: "invisible killer", age: 29, sex: "male "},
{Name: "Sola", age: 22, sex: "male "},
{Name: "fesyo", age: 23, sex: "female "},
{Name: "Love demon pot", age: 18, sex: "male "},
{Name: "Miyazaki", age: 25, sex: "male "},
{Name: "You don't understand", age: 30, sex: "female "}
]

// Var html = ice ("tpl ",{
// Trs: trs,
// Href: "http://images.jb51.net/type4.jpg"
//},{
// Title: function (){
// Return "<p> This is the code snippet output by using the view helper </p>"
//}
//});
Var elem = document. getElementById ('tpl ');
Var tpl = elem. innerHTML;

Var html = ice (tpl ,{
Trs: trs,
Href: http://images.jb51.net/type4.jpg"
},{
Title: function (){
Return "<p> This is the code snippet output by using the view helper </p>"
}
});
Console. log (html );
$ ("# Content" pai.html (html );

</Script>
</Html>


Simple implementation:
Copy codeThe Code is as follows:
(Function (win ){

// Template engine routing function
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 Cache
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'];

// Use different string splicing policies based on the browser
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). result ;};";

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 );

};

// Merge objects
Ice. mix = function (target, source ){
For (var key in source ){
If (source. hasOwnProperty (key )){
Target [key] = source [key];
}
}
};

// Register a function
Ice. on = function (name, fn ){
IHelper [name] = fn;
};

// Clear Cache
Ice. Fetch ache = function (){
ICache = {};
};

// Modify the configuration
Ice. set = function (name, value ){
IConfig [name] = value;
};

// Expose the 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.