按照自己的思路學習Node.Js 隨心出發。EJS是Node.js中express框架中使用的一個模版引擎,當然還有Jade
我的學習就靠網上查資料,沒有買書系統學,自己整理,如果有用了哪位大神的代碼,還請原諒,表森氣.奴婢知錯了
標簽:AaronYang 茗洋 Node.Js Javascript
本篇博客地址:http://www.cnblogs.com/AaronYang/p/4060189.html
開發准備(AaronYang原味)
1你需要一個Node.js開發工具
2基礎回顧,Ejs,因為我是開發ASP.NET MVC的,所以更靠近微軟的一邊,更多的都會和.NET做對比
3GO GO GO!
1、緩存功能,能夠緩存已經解析好的html模版;
2、<% code %>用於執行其中javascript代碼;
3、<%= code %>會對code進行html轉義;
4、<%- code %>將不會進行轉義;
5、支持自定義標簽,比如'<%'可以使用'{{','%>'用'}}'代替;
6、提供一些輔助函數,用於模版中使用
7、利用<%- include filename %>加載其他頁面模版;
1.測試數組(寫完只有一句尼瑪,回到了jsp...的感覺)
/* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express', goods:['褲子','內衣','上衣','小三角'] }); });
我們在對應的views中的index.ejs網頁中,代碼如下:
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css'/> <link rel="stylesheet" href="/stylesheets/cssreset.css"/> <style> body { background-image: url('/images/1.jpg'); } </style> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <!--簡單數組遍歷--> <!--<ul>--> <!--<li>褲子</li>--> <!--<li>褲子</li>--> <!--<li>褲子</li>--> <!--</ul>--> <% for(var i = 0;i < goods.length;i++){ %> <li> <a href='http://<%= goods[i] %>'><%= goods[i] %></a> </li> <% } %> </body> </html>
我們直接可以使用goods對象了,我們通過<%%>這種方式來配合html方式遍歷輸出對象中的值
<%= %>是直接輸出對象的值,你就理解<% js代碼 %>中是js代碼就OK啦

在jsp中是上面import后,輸出對象的值,在.net的對比 razor中的@對象.屬性 就行了
2.局部視圖,類似.net mvc的PartialView,Ejs中也有類似,在早期使用partial('ejs文件',傳給視圖的對象值),現在2014年10月30日18:39:45已經淘汰了
推薦使用include,當然include是不用傳參的,所以你在render頁面傳遞過來的對象叫什么名字,就在分頁面使用那個對象就行了
2.1 在index.js文件中,增加一個變量,鍵值對類型的productlists
Tip:這里額外講個path.dirname的使用,需要require引入 path包才可以使用,這里返回最后一個/ 前面的內容
var path = require('path');
router.get('/', function(req, res) {
console.log(path.dirname('/pro/code/aaronyang'))
res.render('index', {
title: 'Express',
goods:['褲子','內衣','上衣','小三角'],
productlists:[
{
"name":"aaronyang褲子","price":"129元"
},{
"name":"aaronyang內衣","price":"199元"
},{
"name":"aaronyang外套","price":"1098元"
},{
"name":"aaronyang小三角","price":"99元"
}
]
});
});
在views文件夾中增加一個productItem.ejs文件,默認webstorm只有jade,但是你可以Edit File Template增加一個Ejs File,這個很簡單,不講了

代碼如下:
1 <!--以下代碼是aaronyang摸索出來的,博客來自:http://aaronyang.cnblogs.com--> 2 <% if (productlists.length) { 3 productlists.forEach(function(value,index){ 4 %> 5 <div> 6 <span> <%= value.name%></span>:<span><%= value.price %></span> 7 </div> 8 <%})}%>
這里可以直接使用productlists對象,集合可以使用forEach方法,然后配合<%%>的使用就可以了
這里forEach的index參數可以省略,就是個索引0,1,2,3...的東西
效果如下:

OK! 創建一個數據源productlists,然后一個模板頁,使用了數據源的對象,然后頁面中重復使用這段代碼,OK,運行吧!讓奴婢看下

當然,include后面也可以跟路徑,但是不要加引號,后綴名ejs可有可無
<% include productItem %>
附一份css重置html5樣式css的文件,以后有用
1 /* 2 html5doctor.com Reset Stylesheet v1.6.1 3 Last Updated: 2010-09-17 4 Author: Richard Clark - http://richclarkdesign.com 5 */ 6 html, body, div, span, object, iframe, 7 h1, h2, h3, h4, h5, h6, p, blockquote, pre, 8 abbr, address, cite, code, 9 del, dfn, em, img, ins, kbd, q, samp, 10 small, strong, sub, sup, var, 11 b, i, 12 dl, dt, dd, ol, ul, li, 13 fieldset, form, label, legend, 14 table, caption, tbody, tfoot, thead, tr, th, td, 15 article, aside, canvas, details, figcaption, figure, 16 footer, header, hgroup, menu, nav, section, summary, 17 time, mark, audio, video { 18 margin:0; 19 padding:0; 20 border:0; 21 outline:0; 22 font-size:100%; 23 vertical-align:baseline; 24 background:transparent; 25 } 26 body { 27 line-height:1; 28 } 29 article,aside,details,figcaption,figure, 30 footer,header,hgroup,menu,nav,section { 31 display:block; 32 } 33 nav ul { 34 list-style:none; 35 } 36 blockquote, q { 37 quotes:none; 38 } 39 blockquote:before, blockquote:after, 40 q:before, q:after { 41 content:''; 42 content:none; 43 } 44 a { 45 margin:0; 46 padding:0; 47 font-size:100%; 48 vertical-align:baseline; 49 background:transparent; 50 } 51 /* change colours to suit your needs */ 52 ins { 53 background-color:#ff9; 54 color:#000; 55 text-decoration:none; 56 } 57 /* change colours to suit your needs */ 58 mark { 59 background-color:#ff9; 60 color:#000; 61 font-style:italic; 62 font-weight:bold; 63 } 64 del { 65 text-decoration: line-through; 66 } 67 abbr[title], dfn[title] { 68 border-bottom:1px dotted; 69 cursor:help; 70 } 71 table { 72 border-collapse:collapse; 73 border-spacing:0; 74 } 75 /* change border colour to suit your needs */ 76 hr { 77 display:block; 78 height:1px; 79 border:0; 80 border-top:1px solid #cccccc; 81 margin:1em 0; 82 padding:0; 83 } 84 input, select { 85 vertical-align:middle; 86 }
3. express4.x 的 include的版本layout方式
以前express3.x創建項目都有layout.ejs文件,然后render時候,可以指定layout參數,也就是相當於.net的母版頁
好了,既然使用了express4.x,那么自己建立一個吧,我們寫一個header.ejs和footer.ejs
header.ejs
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css'/> <link rel="stylesheet" href="/stylesheets/cssreset.css"/> <style>
body {
background-image: url('/images/1.jpg');
}
</style> </head> <body>
footer.ejs
</body> </html>
然后我們修改index.ejs文件
<% include header%> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <!--簡單數組遍歷--> <!--<ul>--> <!--<li>褲子</li>--> <!--<li>褲子</li>--> <!--<li>褲子</li>--> <!--</ul>--> <% for(var i = 0;i < goods.length;i++){ %> <li> <a href='http://<%= goods[i] %>'><%= goods[i] %></a> </li> <% } %> <hr/> <% include productItem %> <% include footer%>
效果還是一樣的~
4. 使用Ejs自帶的一些方法,增加一個對象testSelfMethod,用於測試,這里使用了Ejs的filter知識中的 upcase
res.render('index', {
title: 'Express',
goods:['褲子','內衣','上衣','小三角'],
productlists:[
{
"name":"aaronyang褲子","price":"129元"
},{
"name":"aaronyang內衣","price":"199元"
},{
"name":"aaronyang外套","price":"1098元"
},{
"name":"aaronyang小三角","price":"99元"
}
],
testSelfMethod:["Aaronyang1","Aaronyang2","Aaronyang3","Aaronyang4","hello aaronyang2014"]
});
使用<%=: %>
<hr/> <%=: testSelfMethod[0] | upcase %>
這里網頁輸出的是 AARONYANG1

upcase方法就是轉換成大寫,更多的方法可以參考https://github.com/tj/ejs
<p><%=: testSelfMethod | last | capitalize %></p>
輸出

從testSelfMethod對象中,最后一個值,將字符串 轉換成 首字母為大寫的字符串,本來hello 變成了Hello
下面我也列出來了幾個,看名字大致也知道幾個怎么用了
first 返回數組的第一個元素
last 返回數組的最后一個元素
capitalize 返回首字母大寫的字符串
downcase 返回字符串的小寫
upcase 返回字符串的大寫
sort 排序
sort_by:'prop' 照指定的prop屬性進行升序排序
size 返回長度,即length屬性,不一定非是數組才行
length
plus:n 加上n,將轉化為Number進行運算
minus:n 減去n,將轉化為Number進行運算
times:n 乘以n,將轉化為Number進行運算
divided_by:n 除以n,將轉化為Number進行運算
join:'val' 將數組用'val'最為分隔符,進行合並成一個字符串
truncate:n 截取前n個字符,超過長度時,將返回一個副本
truncate_words:n 取得字符串中的前n個word,word以空格進行分割
replace:pattern,substitution 字符串替換,substitution不提供將刪除匹配的子串
prepend:val 如果操作數為數組,則進行合並;為字符串則添加val在前面
append:val 如果操作數為數組,則進行合並;為字符串則添加val在后面
map:'prop' 返回對象數組中屬性為prop的值組成的數組
reverse 翻轉數組或字符串
get:'prop' 取得屬性為'prop'的值
Tip:
在Ejs中,可以通過以下方式拓展一個 filter,在node.js中我還不知道怎么加上
ejs.filters.last = function(obj) { return obj[obj.length - 1]; };
OK!
