模板引擎是第三方模塊。讓開發者以更加友好的方式拼接字符串,使項目代碼更加清晰、更加易於維護。css
模板引擎使用步驟:html
1,在命令行工具中使用 npm install art-template 命令進行下載mongodb
2,使用const template = require('art-template')引入模板引擎數據庫
3,告訴模板引擎要拼接的數據和模板在哪 const html = template(‘模板路徑’, 數據);npm
4,使用模板語法告訴模板引擎,模板與數據應該如何進行拼接json
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 // 導入路徑拼接方法 6 const path = require("path"); 7 // 拼接路徑 8 const views = path.join(__dirname,"views","index.art"); 9 10 // template 方法是用來拼接字符串的 11 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 12 // 參數2:對象,即要在模板中顯示的數據 13 // 返回值:拼接好的字符串 14 const html = template(views,{ 15 name:"張三", 16 age:20 17 }); 18 19 console.log(html); 20 21 22 ------------------------------------------------------------ 23 // 使用模板引擎就要有模板,而且模板的後綴名爲 .art 24 // 模板代碼:在模板代碼可使用模板引擎中傳過來的數據 25 26 <!doctype html> 27 <html lang="en"> 28 <head> 29 <meta charset="UTF-8"> 30 <title>Document</title> 31 </head> 32 <body> 33 34 {{name}} 35 36 {{age}} 37 38 39 </body> 40 </html>
模板引擎的語法,主要都是講的在模板中使用這些語法,可讓template(‘模板路徑’, 數據);中的數據在模板中運用。服務器
art-template同時支持兩種模板語法:標準語法和原始語法。app
標準語法可讓模板更容易讀寫,原始語法具備強大的邏輯處理能力。async
標準語法: {{ 數據 }} 原始語法:<%=數據 %>mongoose
輸出語法
標準語法:{{ 數據 }}
原始語法:<%=數據 %>
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 <body> 11 12 <!-- 標準語法 --> 13 <p>{{ name }}</p> 14 <p>{{1+1}}</p> 15 <p>{{ 1+1 == 2 ? "相等":"不相等"}}</p> 16 17 18 <!-- 原始語法 --> 19 <p><%=name%></p> 20 <p><%=1+1%></p> 21 <p><%=1+1 ==2 ?"相等":"不相等"%></p> 22 23 </body> 24 </html>
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 // 用於拼接路徑 5 const path = require("path"); 6 7 const views = path.join(__dirname,"views","01.art"); 8 // template 方法是用來拼接字符串的 9 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 10 // 參數2:對象,即要在模板中顯示的數據 11 // 返回值:拼接好的字符串 12 const html = template(views,{ 13 name:"張三", 14 age:20, 15 }); 16 17 console.log(html); 18 19 /* 20 輸出結果 21 22 <body> 23 <!-- 標準語法 --> 24 25 <p>張三</p> 26 <p>2</p> 27 <p>相等</p> 28 29 <!-- 原始語法 --> 30 <p>張三</p> 31 <p>2</p> 32 <p>相等</p> 33 </body> 34 */
注意:模板引擎中的數據,能夠是template方法中傳過來的數據,也能夠是算數運算符,還能夠是三元運算符。
原文輸出:若是咱們想傳遞HTML代碼,那麼模板引擎並不會將HTML代碼中的特殊符號進行解碼,仍是以編碼的形式顯示。
例如:<h1> 在模板中最後顯示爲 <h1>
那麼咱們就須要讓這些特殊符號在模板中原文顯示。
原文顯示的語法:
標準語法:{{@ 數據 }}
原始語法:<% - 數據 %>
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 <body> 11 12 <!-- 標準語法 --> 13 <p>{{content}}</p> 14 <p>{{@content}}</p> 15 16 <!-- 原始語法 --> 17 <p><%=content%></p> 18 <p><%-content%></p> 19 20 </body> 21 </html>
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 const path = require("path"); 6 7 const views = path.join(__dirname,"views","01.art"); 8 // template 方法是用來拼接字符串的 9 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 10 // 參數2:對象,即要在模板中顯示的數據 11 // 返回值:拼接好的字符串 12 const html = template(views,{ 13 content:"<h1>我是標籤</h1>" 14 }); 15 16 console.log(html); 17 18 /* 19 輸出 20 <body> 21 22 <!-- 標準語法 --> 23 <p><h1>我是標籤</h1></p> 24 <p><h1>我是標籤</h1></p> 25 26 <!-- 原始語法 --> 27 <p><h1>我是標籤</h1></p> 28 <p><h1>我是標籤</h1></p> 29 30 </body> 31 */
1 <!-- 標準語法 --> 2 {{if 條件}} ... {{/if}} 3 {{if v1}} ... {{else if v2}} ... {{/if}} 4 5 <!-- 原始語法 --> 6 <% if (value) { %> ... <% } %> 7 <% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
1 // 標準語法 2 {{if age>18}} 3 年齡大於18 4 {{else if age<15}} 5 年齡小於15 6 {{else}} 7 年齡不符合要求 8 {{/if}} 9 10 11 // 原始語法 12 <%if(age > 18) {%> 13 年齡大於18 14 <% }%> 15 16 // 原始語法 17 <%if (age >18){%> 18 年齡大於18 19 <%}else if(age > 15){%> 20 年齡大於15 21 <%} else {%> 22 年齡不符合要求 23 <%}%>
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 const path = require("path"); 6 7 const views = path.join(__dirname,"views","02.art"); 8 // template 方法是用來拼接字符串的 9 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 10 // 參數2:對象,即要在模板中顯示的數據 11 // 返回值:拼接好的字符串 12 const html = template(views,{ 13 name:"張三", 14 age:20 15 }); 16 17 console.log(html);
1 <!-- 標準語法 --> 2 {{each target}} 3 {{$index}} {{$value}} 4 {{/each}} 5 6 7 <!-- 原始語法 --> 8 <% for(var i = 0; i < target.length; i++){ %> 9 <%= i %> <%= target[i] %> 10 <% } %>
1 <ul> 2 {{each users}} 3 <li> 4 {{$value.name}} 5 {{$value.age}} 6 {{$value.sex}} 7 </li> 8 {{/each}} 9 </ul> 10 11 12 <ul> 13 <% for (var i = 0;i<users.length;i++) {%> 14 <li> 15 <%= users[i].name%> 16 <%= users[i].age%> 17 <%= users[i].sex%> 18 <li> 19 <%}%> 20 </ul>
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 const path = require("path"); 6 7 const views = path.join(__dirname,"views","03.art"); 8 // template 方法是用來拼接字符串的 9 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 10 // 參數2:對象,即要在模板中顯示的數據 11 // 返回值:拼接好的字符串 12 const html = template(views,{ 13 users:[ 14 { 15 name:"張三", 16 age:20, 17 sex:"男" 18 }, 19 { 20 name:"李四", 21 age:30, 22 sex:"男" 23 }, 24 { 25 name:"王五", 26 age:40, 27 sex:"女" 28 }, 29 { 30 name:"趙六", 31 age:20, 32 sex:"女" 33 } 34 ] 35 }); 36 37 console.log(html); 38 39 /* 40 41 <ul> 42 43 <li> 44 張三 45 20 46 男 47 </li> 48 49 <li> 50 李四 51 30 52 男 53 </li> 54 55 <li> 56 王五 57 40 58 女 59 </li> 60 61 <li> 62 趙六 63 20 64 女 65 </li> 66 67 </ul> 68 69 70 <ul> 71 72 <li> 73 張三 74 20 75 男 76 <li> 77 78 <li> 79 李四 80 30 81 男 82 <li> 83 84 <li> 85 王五 86 40 87 女 88 <li> 89 90 <li> 91 趙六 92 20 93 女 94 <li> 95 96 </ul> 97 98 */
子模板的做用:能夠將網站公共區塊(頭部、底部)抽離到單獨的文件中,在使用子模板語法將這些公共的文件引入便可。
1 <!-- 標準語法 --> 2 {{include '模板路徑'}} 3 4 <!-- 原始語法 --> 5 <% include('模板路徑') %>
1 // 標準語法 2 {{ include './common/header.art'}} 3 // 原始語法 4 <% include('./common/header.art')%> 5 <div>{{msg}}</div> 6 // 原始語法 7 <% include('./common/footer.art')%> 8 // 標準語法 9 {{ include './common/footer.art'}}
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 const path = require("path"); 6 7 const views = path.join(__dirname,"views","04.art"); 8 // template 方法是用來拼接字符串的 9 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 10 // 參數2:對象,即要在模板中顯示的數據 11 // 返回值:拼接好的字符串 12 const html = template(views,{ 13 msg:"我是首頁" 14 }); 15 16 console.log(html); 17 18 19 /* 20 * 21 輸出結果 22 我是頭部 23 24 <div>我是首頁</div> 25 26 我是底部 27 * */
使用模板繼承能夠將網站HTML骨架抽離到單獨的文件中,其餘頁面模板能夠繼承骨架文件。
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>HTML骨架模板</title> 6 // 留下坑讓繼承的代碼去填寫 7 {{block 'head'}}{{/block}} 8 </head> 9 <body> 10 // 留下坑讓繼承的代碼填寫 11 {{block 'content'}}{{/block}} 12 </body> 13 </html> 14 15 -------------------------------------------------- 16 // 繼承代碼,填寫坑 17 {{extend './layout.art'}}// 繼承的代碼 18 {{block 'head'}} <link rel="stylesheet" href="custom.css"> {{/block}} 19 {{block 'content'}} <p>This is just an awesome page.</p> {{/block}}
1 // 父模板 2 <!doctype html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7 {{block "link"}} {{/block}} 8 </head> 9 <body> 10 {{block "content"}} {{/block}} 11 </body> 12 </html> 13 14 ---------------------------------------------- 15 // 子模板,用來繼承父模板 16 {{extend './common/layout.art'}} 17 18 {{block 'content'}} 19 <p>{{ msg }}</p> 20 {{/block}} 21 22 {{block 'link'}} 23 <link rel="stylesheet" type="text/css" href="./main.css"> 24 {{/block}}
1 // 導入模板引擎 2 // 返回的template是一個方法 3 const template = require("art-template"); 4 5 const path = require("path"); 6 7 8 const views = path.join(__dirname,"views","05.art"); 9 // template 方法是用來拼接字符串的 10 // 參數1:模板的路徑 絕對路徑。絕對路徑最後一個爲文件名。文件名的後綴要爲.art 11 // 參數2:對象,即要在模板中顯示的數據 12 // 返回值:拼接好的字符串 13 const html = template(views,{ 14 msg:"我是首頁" 15 }); 16 17 console.log(html);
模板配置可讓代碼的使用變得簡單。而且能夠向模板中導入一些方法,和變量在模板中使用。
1,向模板中導入變量 template.defaults.imports.變量名 = 變量值;// 還能夠是將一些方法導入到模板中使用
2,設置模板根目錄 template.defaults.root = 模板目錄;
3,設置模板默認後綴 template.defaults.extname = '.art'
1 // 模板 2 {{ format('yyyy-MM-dd',time)}} 3 4 5 ---------------------------------------------------------- 6 // 配置語法和導入語法 7 const template = require('art-template'); 8 const path = require('path'); 9 10 // 第三方用於處理時間的模塊 11 const format = require('date-format'); 12 // 設置模板的根目錄 13 template.defaults.root = path.join(__dirname, 'views'); 14 15 // 導入模板變量(方法) 16 template.defaults.imports.format = format; 17 18 // 配置模板的默認後綴 19 template.defaults.extname = ".art"; 20 21 const html = template('06', { 22 time: new Date() 23 }); 24 25 console.log(html);
實現功能:
1,創建項目文件夾並生成項目描述文件
2,建立網站服務器實現客戶端和服務器端通訊
3,鏈接數據庫並根據需求設計學員信息表
4,建立路由並實現頁面模板呈遞
5,實現靜態資源訪問
6,實現學生信息添加功能
7,實現學生信息展現功能
第一步:創建項目文件夾並生成項目描述文件
在students文件夾中建立model文件夾,用來存放有關數據庫的代碼
在students文件夾中建立public文件夾,用來存放靜態資源相關的代碼
在students文件夾中建立views文件夾,用來存放模板的文件(.art文件裏面是HTML代碼)
package.json 文件中存放項目描述信息
第二步:建立網站服務器實現客戶端和服務器端通訊
1 // 引入http模塊 2 const http = require("http"); 3 4 // 建立服務 5 const app = http.createServer(); 6 7 // 添加請求事件 8 app.on("request", (req, res) => { 9 // req爲請求對象,res爲響應對象 10 res.edn("OK"); 11 }); 12 13 app.listen(80); 14 console.log("服務器開啓成功");
第三步:鏈接數據庫並根據需求設計學員信息表
1 // 引入數據庫模塊 2 const mongoose = require("mongoose"); 3 // 鏈接數據庫 4 mongoose.connect("mongodb://localhost/playground",{ useUnifiedTopology: true,useNewUrlParser: true}) 5 .then(()=>console.log("數據庫鏈接成功")) 6 .catch(()=>console.log("鏈接失敗")); 7 8 --------------------------------------------------------------- 9 const mongoose = require("mongoose"); 10 11 // 建立學生的集合規則 12 const studentsSchema = new mongoose.Schema({ 13 name:{ 14 type:String, 15 require:true, 16 minlength:2, 17 maxlength:10 18 }, 19 age:{ 20 type: Number, 21 min:10, 22 max:25, 23 }, 24 sex:{ 25 type:String, 26 }, 27 email:String, 28 hobbies:[String], 29 collage:String, 30 enterDate:{ 31 type:Date, 32 default:Date.now() 33 } 34 }); 35 36 // 使用集合規則建立集合 37 const Student = mongoose.model("Student",studentsSchema); 38 39 // 將學生信息集合進行導出 40 module.exports = Student; 41 42 43 --------------------------------------------------------------------- 44 // 引入http模塊 45 const http = require("http"); 46 // querystring 模塊 47 const querystring = require("querystring"); 48 // 導入鏈接數據庫模塊 49 require("./model/connect"); 50 // 導入學生集合規則構造函數 51 const Student = require("./model/user"); 52 // 建立服務 53 const app = http.createServer(); 54 // 添加請求事件 55 app.on("request", (req, res) => { 56 // req 爲請求參數。res爲響應參數 57 res.end("OK"); 58 }); 59 60 app.listen(80); 61 console.log("服務器開啓成功");
第四步:建立路由並實現頁面模板呈遞
使用第三方模塊router來實現路由,不在本身寫路由
功能:實現路由
使用步驟:
1,獲取路由對象
2,調用路由對象提供的方法建立路由
3,啓用路由,使路由生效
1 // 1,導入第三方模塊 2 const getRouter = require('router') 3 // 2,獲取路由對象 4 const router = getRouter(); 5 // 3,調用路由對象提供的方法建立路由 6 router.get('/add', (req, res) => { 7 res.end('Hello World!') 8 }) 9 // 啓用路由,在事件請求對象中 10 server.on('request', (req, res) => { 11 // 參數一、參數2都爲事件請求對象中的參數。參數3位回調函數而且爲必選參數,這裏不用先寫一個空函數 12 router(req, res,()=>{}) 13 })
第五步:實現靜態資源訪問
使用第三方模塊 serve-static。實現靜態資源訪問服務
步驟:
1,引入serve-static模塊獲取建立靜態資源服務功能的方法
2,調用方法建立靜態資源服務並指定靜態資源服務目錄
3,啓用靜態資源服務功能
1 // 引入第三方模塊,返回的是一個方法 2 const serveStatic = require('serve-static') 3 // 調用該方法建立靜態訪問。指定靜態資源所在文件夾 4 const serve = serveStatic('public') 5 server.on('request', () => { 6 // 開啓靜態資源訪問功能,req,res參數都爲事件請求對象的參數。第三個參數爲回調函數,必填參數,如今不須要使用,傳遞一個空函數 7 serve(req, res,()=>{}); 8 }) 9 server.listen(3000)
第六步:實現學生信息添加功能
實現步驟:
1,在模板的表單中指定請求地址與請求方式
2,爲每個表單項添加name屬性
3,添加實現學生信息功能路由
4,接收客戶端傳遞過來的學生信息
5,將學生信息添加到數據庫中
6,將頁面重定向到學生信息列表頁面
第七步:實現學生信息展現功能
實現步驟:
1,從數據庫中將全部的學生信息查詢出來
2,經過模板引擎將學生信息和HTML模板進行拼接
3,將拼接好的HTML模板響應給客戶端
--------------------------
--------------------------
1 // 引入數據庫模塊 2 const mongoose = require("mongoose"); 3 // 鏈接數據庫 4 mongoose.connect("mongodb://localhost/playground",{ useUnifiedTopology: true,useNewUrlParser: true}) 5 .then(()=>console.log("數據庫鏈接成功")) 6 .catch(()=>console.log("鏈接失敗")); 7 8 --------------------------------------------------------------- 9 const mongoose = require("mongoose"); 10 11 // 建立學生的集合規則 12 const studentsSchema = new mongoose.Schema({ 13 name:{ 14 type:String, 15 require:true, 16 minlength:2, 17 maxlength:10 18 }, 19 age:{ 20 type: Number, 21 min:10, 22 max:25, 23 }, 24 sex:{ 25 type:String, 26 }, 27 email:String, 28 hobbies:[String], 29 collage:String, 30 enterDate:{ 31 type:Date, 32 default:Date.now() 33 } 34 }); 35 36 // 使用集合規則建立集合 37 const Student = mongoose.model("Student",studentsSchema); 38 39 // 將學生信息集合進行導出 40 module.exports = Student; 41 42 43 --------------------------------------------------------------------- 44 // 引入http模塊 45 const http = require("http"); 46 // 引入router模塊 47 const getRouter = require("router"); 48 // 引入path模塊 49 const path = require("path"); 50 // 引用靜態資源訪問模塊 51 const serveStatic = require("serve-static"); 52 // 引入模板引擎 53 const template = require("art-template"); 54 // 獲取路由對象 55 const router = getRouter(); 56 // 實現靜態資源訪問 57 const serve = serveStatic(path.join(__dirname, "public")); 58 // querystring 模塊 59 const querystring = require("querystring"); 60 // 處理日期模塊 61 const dateformat = require("dateformat"); 62 63 // 導入到模板中dateformat方法 64 template.defaults.imports.dateformat= dateformat; 65 66 // 配置模板的根目錄 67 template.defaults.root = path.join(__dirname, "views"); 68 69 70 // 建立路由 71 // 呈遞學生檔案信息頁面 72 router.get("/add", (req, res) => { 73 let html = template("index.art", {}); 74 75 res.end(html); 76 }); 77 78 // 呈遞學生檔案信息列表頁面 79 router.get("/list", async (req, res) => { 80 // 查詢學生信息 81 let students = await Student.find(); 82 console.log(students); 83 let html = template("list.art", { 84 students:students 85 }); 86 87 res.end(html); 88 }); 89 // 路由:實現post請求的 /add 路由 90 router.post("/add",(req,res)=>{ 91 // 接收post請求參數 92 let formData = ""; 93 94 req.on("data",param =>{ 95 formData += param; 96 }); 97 98 req.on("end",async ()=>{ 99 await Student.create(querystring.parse(formData)); 100 101 res.writeHead(301,{ 102 Location:"/list" 103 }); 104 res.end(); 105 }); 106 }); 107 108 // 導入鏈接數據庫代碼 109 require("./model/connect"); 110 // 導入集合構造函數代碼 111 const Student = require("./model/user"); 112 // 建立服務器 113 const app = http.createServer(); 114 // 爲服務器添加請求事件 115 app.on("request", (req, res) => { 116 // 啓用路由 117 router(req, res, () => { 118 }); 119 120 // 啓用靜態資源訪問功能 121 serve(req, res, () => { 122 }); 123 }); 124 125 app.listen(80); 126 console.log("服務器開啓成功");
------------