node+express+ejs
根据这篇文章整理
假设此时你已经安装了node
目录结构
app
--views
--pages
--index.ejs
--partials
--head.ejs
--header.ejs
--footer.ejs
server.js
package.json
首先肯定是安装express和ejs
package.json里:
{
"name": "app",
"main":"server.js",
"description": "hello world test app",
"version": "0.0.1",
"dependencies": {
"ejs": "^1.0.0",
"express": "^4.6.1"
}
}
<p>dependencies就是要依赖的包了</p>
<p>在命令行里执行</p>
npm install
<p>就会安装项目所依赖的包了</p>
server.js:
//server.js
var express = require('express');
var app = express();
//设置模板引擎为ejs
app.set('view engine','ejs');
//使用res.render 渲染 ejs 模板
//res.render 会去views目录里找对应的文件
//index page
app.get('/',function(req,res){
res.render('pages/index');
});
//设置监听端口
app.listen(8888);
console.log('8888 is the magic port');
<p>然后,当然是</p>
node server.js
<p>现在可以打开浏览器,输入</p>
http://localhost:8888
<p>来看看刚才写的东西了。</p>
<p>当然,它必须是个空白的页面</p>
ejs partials
footer.ejs,head.ejs,header.ejs
<p>其实这里就是放的公共的文件,头尾,所以你当然可以把head.ejs和header.ejs合并成一个</p>
herd.ejs
<!-- views/partials/head.ejs -->
<meta charset="UTF-8">
<title>Super Awesome</title>
<!-- CSS (load bootstrap from a CDN) -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
body { padding-top:50px; }
</style>
header.ejs
<!-- views/partials/header.ejs -->
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
EJS Is Fun
</a>
</div>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</div>
</nav>
footer.ejs
<!-- views/partials/footer.ejs -->
<p class="text-center text-muted">© Copyright 2014 The Awesome People</p>
<p>那么,如何使用这些公共部分呢,看下index.ejs的代码</p>
index.ejs
<!-- views/pages/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
在ejs中,使用<% include FILENAME %>
来引用ejs文件,不需要后缀。
现在再刷新浏览器,就可以看到正常的页面了
如果你已经完成了,可以试着自己写一下about页面