nodejs express ejs

//express-demo.js

var ejs = require('ejs');
var express = require('express');
var app = express();
 
app.get('/', function (req, res) {
res.send('Hello World express');
})
app.get('/ejs-demo', function (req, res) { showDemo(req, res) } );

var server = app.listen(8001, function () {
var host = server.address().address
var port = server.address().port
console.log("應用實例,訪問地址爲 http://%s:%s", host, port)
})


//show demo of ejs
var showDemo = function(req, res){
var users = ['郭建國', '劉幸福', '張富強', '王大寶', '李鋼蛋'];
ejs.renderFile('./view/demo.ejs', { users: users }, function(err, str) {
if (err) {
console.log(err);
} else {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.write(str);
res.end();
}
});
}
 

 

 
 
 
 
//demo.ejs
<body>

<%- include('./common-header.ejs'); %>
<h1>關於我</h1>

<ul>
<% for(var i = 0; i < users.length; i++) { %>
<% var user = users[i]; %>
<li><%= user %></li>
<% } %>
</ul>
</body>

 

 
 
 
//common-header.ejs
<header>
<a href="/">個人網站</a>
<nav>
<li><a href="aboutme">關於我</a></li>
<li><a href="projects">項目介紹</a></li>
<li><a href="blog">我的博客</a></li>
</nav>
</header>
相關文章
相關標籤/搜索