nodejs基於ejs的一個簡單demo
阿新 • • 發佈:2018-12-07
1檔案大概目錄
2.建立專案檔案,先建一個ejs_demo資料夾,在ejs_demo執行下面命令,初始化倉庫,一路回車:
npm init
3.安裝兩個ejs和express外掛:
npm install ejs --save
npm install express --save
4.建立檔案app.js,寫上以下程式碼:
var http=require("http"); var express=require("express"); var app=express(); var path = require('path'); // 1.在app.js的頭上定義ejs: var ejs = require('ejs'); //定義變數 var tem={ message:"我是中間部分" }; //建立伺服器 //在控制檯輸入node app.js啟動伺服器 http.createServer(app).listen(8080,function(){ console.log("伺服器地址為:http://localhost:8080"); }); //掛載靜態資源處理中介軟體,設定css或者js引用檔案的靜態路徑 app.use(express.static(__dirname+"/public")); // 或者以下這個也可以 // app.use(express.static(path.join(__dirname, 'public'), {maxAge: 36000})); //設定模板檢視的目錄 app.set("views","./public/views"); //設定是否啟用檢視編譯快取,啟用將加快伺服器執行效率 app.set("view cache",true); // 2.註冊html模板引擎: app.engine('html',ejs.__express); //設定模板引擎的格式即運用何種模板引擎 app.set("view engine","html"); //設定路由 app.get("/index",function(req,res){ res.render("index",{title:tem.message}); });
5.寫index.html檔案
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>EJS</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="/css/main.css" rel="stylesheet"> </head> <body> <%- include("./header.html") %> <h1><%=title%></h1> <%- include("./footer.html") %> </body> </html>
6.寫header.html檔案:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>我是頭部</h1> </body> </html>
7.寫footer.html檔案:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>我是尾部</h1>
</body>
</html>
8.寫main.css檔案:
h1{
width:80%;
height:100px;
background:green;
margin:20px auto;
text-align: center;
line-height:100px;
}
9.在ejs_demo資料夾下執行以下命令:
node app.js
10.在瀏覽器輸入以下域名:
http://localhost:8080/index
11.最後效果圖: