There are many options for Node open source templates, but it is recommended that elderly people like me use EJS. It is natural to use EJS with experience in Classic ASP/PHP/JSP. That is to say, you can arrange JavaScript code in the <%...%> block and use <%=output variable %> in the most traditional way (in addition, <%-output variables will not escape symbols such as &). The EJS installation command is as follows:
npm install ejs
JS call
There are two main methods called by JS:
ejs.compile(str, options); // => Function ejs.render(str, options); // => str
In fact, EJS can be used independently from Express, 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 the string of the template, and the template is as follows. <% if (names.length) { %> <ul> <% names.forEach(function(name){ %> <li foo='<%= name + "'" %>'><%= name %></li> <% }) %> </ul> <% } %>names become local variables.
Option parameters
The second parameter is data, which is usually an object. This object can be regarded as an option, which means that the data and selection are on the same object.
If you don't want to have disks every time, you need to cache the template and set options.filename. 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' }) users.push({ name: 'Jane', age: 6, species: 'ferret' }) var ret = ejs.render(str, { users: users, filename: path }); console.log(ret);inculde command
And, if you want to
<ul> <% users.forEach(function(user){ %> <% include user/show %> <% }) %></ul>Generally, inserting a common template, that is, introducing a file, you must set the filename option to start the include feature, otherwise include will not know the directory where it is located.
template:
<h1>Users</h1> <% function user(user) { %> <li><strong><%= user.name %></strong> is a <%= user.age %> year old <%= user.species %>.</li> <% } %> <ul> <% users.map(user) %> </ul>EJS supports compiling templates. After template compilation, there is no IO operation, it will be very fast and can be used for local variables. The following example user/show ignores the ejs extension:
<ul> <% users.forEach(function(user){ %> <% include user/show %> <% }) %> </ul>Custom CLOSE TOKEN
If you plan to use <h1>{{= title }}</h1> generally non-<%%> tag, you can also customize it.
var ejs = require('ejs'); ejs.open = '{{'; ejs.close = '}}'; Format output is also OK. ejs.filters.last = function(obj) { return obj[obj.length - 1]; }; Called:<p><%=: users | last %></p>EJS also supports browser environments.
<html> <head> <script src="../ejs.js"></script> <script id="users" type="text/template"> <% if (names.length) { %> <ul> <% names.forEach(function(name){ %> <li><%= name %></li> <% }) %> </ul> <% } %> </script> <script> onload = function(){ var users = document.getElementById('users').innerHTML; var names = ['loki', 'tobi', 'jane']; var html = ejs.render(users, { names: names }); document.body.innerHTML = html; } </script> </head> <body> </body> </html> I wonder if EJS can output multi-layer JSON objects?By the way, some netizens revealed that jQ master John wrote a 20-line template several years ago, which is ashamed, similar to EJS but short and concise!
Simple and practical js template engine
A js template engine with less than 50 lines supports various js syntax:
<script id="test_list" type="text/html"> <%= for(var i = 0, l = p.list.length; i < l; i++){ var stu = p.list[i]; =%> <tr> <td<%=if(i==0){=%><%=}=%>><%==stu.name=%></td> <td><%==stu.age=%></td> <td><%==(stu.address || '')=%></td> <tr> <%= } =%> </script>"<%= xxx =%>" is the js logic code, and "<%== xxx =%>" is the direct output variable, similar to the function of echo in php. "p" is the kv object parameter when calling the following build method. It can also be set to another parameter name when calling "new JTemp"
Called:
$(function(){ var temp = new JTemp('test_list'), html = temp.build( {list:[ {name:'Zhang San', age:13, address:'Beijing'}, {name:'Li Si', age:17, address:'Tianjin'}, {name:'Wang Wu', age:13} ]}); $('table').html(html); });After the above temp is generated, the build method can be called multiple times to generate html. Here is the code for the template engine:
var JTemp = function(){ function Temp(htmlId, p){ p = p || {};//Configuration information, in most cases, 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{//Normal statement str_ += 'f+=' + p.substring(1) + ';'; } str = str.substring(e + el); s = str.indexOf(_.TEMP_S); } str_ += 'f+=/'' + str + '/';'; str_ = str_.replace(//n/g, '');//handle line-break 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 convert the template code into a function that splices strings, and each time you take the data call function.
Because it is mainly used for mobile phones (webkits), the efficiency of string splicing is not considered. If it needs to be used by IE, it is best to change the string splicing method to the form of Array.push().
ejs template layout layout
1. If you are unwilling 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 are unwilling 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 separately. Global settings can be used:
app.set("view options",{ "layout":false});4. In ejs, the default closing tag is <% .. %>, and we can also define our own tags. For example:
app.set("view options",{ "open":"{{", "close":"}}"});5. Local layout
In web applications, it is often necessary to repeatedly display a certain content, such as the user comment function, which requires the repeated display of each user's comment. At this time, we can achieve it through loops. However, it can also be implemented using [partial template] (partial). For example:
First, we create a local template./views/comment.ejs:
<div> <div><%=comment.user%></div> <div><%=comment.content%></div> </div>
Note: Here is comment.xxxx
Then in ./views/index.ejs, call comment via partial
this is <%=title%>! <br/> <%- partial("comment", comments)%>Note: Here is partial("comment.ejs", comments); <-- The word should be plural.
Finally, in the 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 in the code are the same as the comments variable name of index.ejs, and in comment.ejs called by partial, the singular form of comment is used.
When lists are displayed, the scenario we usually encounter is to display the first element or the last element specially. In part, we can use the built-in variables in Express to determine whether the current object is the first element or the last element, for example:
<div> <div><%=comment.user%></div> : <div><%=comment.content%></div> </div>
In this way, there will be an extra firstitem in the class of the first comment.
Similar built-in variables include:
(1) FirstInCollection is true if it is the first element of the array
(2) indexInCollection The index of the current element in the array
(3) lastInCollection is true if it is the last element of the array
(4) CollectionLength
Finally, there is the path search problem when partial calls the template:
(1) partial("edit") will look for edit.ejs file in the same directory.
(2) partial("../message") will look for the message.ejs file of the previous level directory.
(3) partial("users") will look for users.ejs file. If users.ejs does not exist, the /users/index.ejs file will be searched.
(4) <%= users %> will escape the content. If you want to escape it, you can use <%- users %>