Introduction to the Node.js Web Template engine Ejs tutorial _node.js

Source: Internet
Author: User

Node Open Source template has a lot of choices, but it is recommended that old people like me to use EJS, have Classic asp/php/jsp experience to use EJS to do it naturally, that is, you can arrange JavaScript code in <%...%> block, take advantage of the most traditional <%= output Variable%> (in addition <%-output variables are not escaped for symbols such as &). Install the EJS command as follows:

NPM Install Ejs

JS Call
JS calls the Main method has two:

Ejs.compile (str, options); 
=> Function 
 
ejs.render (str, options); 
=> Str 

In fact, EJS can be isolated from Express use, for example:

var Ejs = require ('), str = require (' FS '). Readfilesync (__dirname + '/list.ejs ', ' UTF8 '); 
 
var ret = Ejs.render (str, { 
 names: [' foo ', ' Bar ', ' Baz '] 
}); 
 
Console.log (ret); 
See Ejs.render (), the first parameter is a string of templates, the template is as follows.
<% if (names.length) {%> 
 <ul> 
 <% names.foreach (function (name) {%> <li foo= 
  ' <%= name + "'"%> ' ><%= name%></li> 
 <%})%> 
 </ul> 
<%}%> 

Names becomes a local variable.

Option parameters
The second parameter is data, which is generally an object. This object can be viewed as an option, which means that both the data and the selection are on the same object.
If you do not want to disk every time, you need to cache the template, set the Options.filename can be. For example:

var Ejs = require ('.. /') 
 , fs = require (' FS ') 
 , Path = __dirname + '/functions.ejs ' 
 , str = fs.readfilesync (path, ' UTF8 '); 
 
var users = []; 
 
Users.push ({name: ' Tobi ', age:2, Species: ' Ferret '}) 
Users.push ({name: ' Loki ', age:2, Species: ' Ferret '}) 
us Ers.push ({name: ' Jane ', Age:6, Species: ' Ferret '}) 
 
var ret = Ejs.render (str, { 
 users:users, 
 Filename:pat H 
}); 
 
Console.log (ret); 

Inculde directives
also, if you want to

<ul>
 <% Users.foreach (function (user) {%>
 <% include user/show%> <%
 })%>
</ul>

To insert a common template, that is, to introduce a file, you must set the filename option to start the Include feature, otherwise the include does not know the directory.
templates:

 
 

EJS supports compiling templates. After the template is compiled, there is no IO operation, it is very fast, and you can public local variables. The following example user/show ignores Ejs extensions:

<ul> 
 <% Users.foreach (function (user) {%> 
 <% include user/show%> <% 
 })%> 
</ul> 

Custom Close TOKEN
You can also customize it if you plan to use the
var Ejs = require (' Ejs '); 
Ejs.open = ' {{'; 
Ejs.close = '}} '; 
Formatted output can also be oh.
Ejs.filters.last = function (obj) {return 
 obj[obj.length-1]; 
 
Call:
<p><%=: Users | Last%></p> 
EJS also supports the browser environment.
 
  
I wonder if EJS can output a multi-tiered JSON object?

Yes, there are netizens to say, JQ John a few years ago wrote 20 lines of templates, shame, and EJS similar but dapper!

Simple and practical JS template engine
less than 50 lines of JS template engine, support a variety of JS syntax:

<script id= "test_list" type= "text/html" > 
<%= 
 for (var i = 0, L = p.list.length; i < L; i++) { 
  var st U = p.list[i]; 
=%> 
 <tr> 
  <td<%=if (i==0) {=%> class= "a" <%=}=%>><%==stu.name=%></ td> 
  <td><%==stu.age=%></td> 
  <td><%== (stu.address | | ') =%></td> 
 <tr> 
 
<%= 
 } 
=%> 


"<%= xxx =%>" is the JS logic code, "<%== xxx =%>" is a direct output variable, similar to the role of PHP Echo. "P" is the K-v object argument when calling the build method below, or it can be set to a different parameter name when calling "New Jtemp"

Call:

$ (function () { 
 var temp = new Jtemp (' Test_list '), 
  html = temp.build ( 
   {list:[ 
     {name: ' John ', Age:13, Address: ' Beijing '}, 
    {name: ' Dick ', age:17, Address: ' Tianjin '}, 
    {name: ' Harry ', age:13} 
   ]}; 
 $ (' table '). HTML (HTML); 
}; 

After the temp build above, you can call the build method multiple times to generate HTML. The following is the code for the template engine:

var jtemp = function () {function Temp (Htmlid, p) {p = p | | 
  {};//configuration information, most of which can be default this.htmlid = Htmlid; 
  This.fun; This.oname = P.oname | | 
  ' P '; This. temp_s = P.temps | | 
  ' <%= '; This. temp_e = P.tempe | | 
  ' =%> '; 
 This.getfun (); 
   } Temp.prototype = {getfun:function () {var _ = this, str = $ (' # ' + _.htmlid). html (); 
   if (!STR) _.err (' Error:no temp!! '); var str_ = ' var ' + _.oname + ' =this,f=\ '; ', S = Str.indexof (_. temp_s), E =-1, p, sl = _. Temp_s.length, el = _. 
   Temp_e.length; for (; s >= 0;) {e = Str.indexof (_. 
    TEMP_E); if (E < s) alert (':( 
    error!! '); 
    Str_ + = ' f+=\ ' + str.substring (0, s) + '; '; 
    p = _.trim (str.substring (S+SL, E)); 
    if (p.indexof (' = ')!== 0) {//JS statement str_ + = p; 
    }else{//General statement Str_ + + ' f+= ' + p.substring (1) + '; 
    str = str.substring (e + el); s = Str.indexof (_. 
   temp_s); 
   } str_ + = ' f+=\ ' + str + '; '; Str_ = Str_.replace (/\n/g, ")//Processing line newline var fs = str_ + ' return f; '; 
  This.fun = Function (FS); 
  }, Build:function (p) {return this.fun.call (p); 
  }, Err:function (s) {alert (s); }, Trim:function (s) {return S.trim?s.trim (): S.replace (/(^\s*) | ( 
  \s*$)/g, ""); 
 } 
 }; 
return Temp; 

 }();

The core is to turn the template code into a concatenation string function, each time the data call this function.

Because the main is for mobile phone (WebKit) use, so do not consider the efficiency of string stitching, if you need to use for IE, it is best to string stitching method to Array.push () Form.

Ejs Template Layout Layout
1. If you do not want to use the default Layout.ejs, you can specify it yourself. For example:

Res.render ("index", {"title": "Test", "Layout": "Main"});
or
res.render ("index", {"title": "Test", "Layout": "Main.ejs"});

2. If you do not want to use layout, you can set layout to False, for example:

Res.render ("index", {"Layout": false});

3. If you do not want each request to be set up individually once. You can use global settings:

App.set ("View Options", {                       
 "layout": false
});

4. In Ejs, the default closing mark is <%. %>, we can also define our own labels. For example:

App.set ("View Options", {                     
 "open": "{{",                     
 "Close": "}}"
});

5. Local layout
In Web applications, it is often necessary to repeatedly display a content, such as: User comment function, need to repeat the comments of each user, this time, we can through the loop to achieve. However, it can also be implemented using local templates (partial). For example:

First we build a local template./views/comment.ejs:

<div class= "Comment_item" >               
 <div class= "Comment_user" ><%=comment.user%></div> 
 <div class= "comment_content" ><%=comment.content%></div> 
</div>

Note: This is comment.xxxx.

Then in./views/index.ejs, call comment by partial

This is <%=title%>!               
<br/>               
<%-Partial ("comment", comments)%>

Note: Here is partial ("Comment.ejs", comments); <--words in plural.

Finally, in router, call Index.ejs.

 App.get ("/", function (req,res) {             
 res.render ("index", {"title": "Test", "layout": false, "comments": [             
  {"User": "Gainover", "Content": "Test1"},             
  {"User": "Zongzi", "Content": "Test2"},             
  {"User": "Maomao", "Content": "Test3" }             
 ]});             
});

Note: The comments and Index.ejs comments variable names in the code are the same, and in the Comment.ejs that partial calls, the singular form of the comment is used.

When the list is displayed, the scenario we usually encounter is a special display of the first element or the last element. In partial, we can determine whether the current object is the first element or the last element through the express built-in variable, for example:

 <div class= "Comment_item<%if (firstincollection) {%> firtitem <%}%>" > 
 <div class= "Comment_ User "><%=comment.user%></div>:        
 <div class=" Comment_content "><%=comment.content% ></div>       
</div>

There will be one more firstitem in the class of the first comment.

Similar built-in variables are:
(1) Firstincollection True if it is the first element of the array
(2) indexincollection The index of the current element in the array
(3) Lastincollection True if it is the last element of the array
(4) The length of the collectionlength array

Finally, the partial path lookup problem when the template is invoked:

(1) Partial ("edit") looks for Edit.ejs files in the same directory.
(2) Partial (".. /message ") will look for Message.ejs files in the previous level of the directory.
(3) Partial ("users") looks for the Users.ejs file, and if Users.ejs does not exist, the/users/index.ejs file is found.

(4) <%= users%> will be able to escape the content, do not want to escape, you can use the <%-users%>

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.