ejs模板學(xué)習(xí)起來非常簡單,類似html,標(biāo)簽和jsp里的java代碼標(biāo)簽差不多.
常用標(biāo)簽:
<%%>
<%=%>
<%-%>
<%include %>
<%for(){}%>
<%if(){}%> if-else
簡單介紹
1.<%%>標(biāo)簽里可以寫js代碼-定義變量
<% var data = 50;var hello = '<h3>hello world</h3>' %>
2.<%=%>和<%-%> 區(qū)別 前者不會編譯,后者會編譯
<h2>data的值為 : <%=data%></h2>
<%=hello%><br>
<%-hello%>
運(yùn)行結(jié)果:
image
3.<%include xxx%> 包含其他ejs文件,一般用于包含頭部引用和頁面相同的部分
4.<%for%>一般用于后端查詢出一段數(shù)組數(shù)據(jù),前端展示
后端虛擬數(shù)據(jù):
req.titles = [
{name:'nodejs官網(wǎng)',url:'http://nodejs.org/'},
{name:'express官網(wǎng)',url:'http://www.expressjs.com.cn/'},
{name:'ejs官網(wǎng)',url:'http://www.embeddedjs.com/'},
{name:'javascript官網(wǎng)',url:'http://www.w3school.com.cn/js/'}
];
res.render('ejs',req);
前端代碼:
<%for(var i=0; i < titles.length; i++){ var title = titles[i]; %>
<h3>標(biāo)題 : <%=title.name%> ,地址 : <%=title.url%> </h3>
<%}%>
運(yùn)行效果:
image
5.<%if%> 判斷 一般都和for結(jié)合使用,也可單獨(dú)使用
后端虛擬數(shù)據(jù)
req.numbers = [
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random()),
parseInt(10*Math.random())
];
res.render('ejs',req);
前端代碼:
<%for(var i=0; i < numbers.length; i++){ var number = numbers[i]; %>
<%if(number < 5){%>
<h3>獲取后端值小于5,值為 : <%=number%></h3>
<%}else{%>
<h3>獲取后端值大于4,值為 : <%=number%></h3>
<%}%>
<%}%>
運(yùn)行結(jié)果:
image