// ejs-demo.js
var http = require('http'); var ejs = require('ejs'); var url = require('url'); // 搭建 HTTP 服務器 var server = http.createServer(function(req, res) { var urlObj = url.parse(req.url, true); switch (urlObj.pathname) { case '': case '/': showDemo(req, res); break; case '/header': showHeader(req, res); break; } }).listen(8002); console.log('Server running at http://127.0.0.1:8002/'); //show demo 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(); } }); } //show header var showHeader = function(req, res){ var users = ['a','b']; ejs.renderFile('./view/common-header.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>