@kexinWeb
2017-02-22T08:38:42.000000Z
字数 1903
阅读 2907
ejs node express
cd <项目文件夹路径>cnpm install express --save
cd <项目文件夹路径>cnpm install ejs --save
整个项目文件夹的结构如下:
views
---home.html
---article.htmlapp.js
package.json
README.md
.gitignore
其中app.js是入口文件,views文件夹下面放置的是需要渲染的模板文件,package.json是整个项目的配置文件,.gitignore文件里面写明文件pull到github时不需要上传的文件或文件夹,如 node_modules文件夹
//加载express模块const express = require('express');//加载ejs模块const ejs = require('ejs');//加载path模块,path模块中包含许多处理文件路径的工具const path = require('path');//创建一个express实例let app = express();//注册模板文件的后缀名为html,默认为ejsapp.engine('html', ejs.__express);//设置模板文件存放的目录,默认是与app.js同级下views文件夹//path.join()用于路径拼接,可以根据当前的操作系统的类型正确选用文件路径拼接字符,linux是/,window是\app.set('views', path.join(__dirname, '/views'));//设置模板文件的后缀名为html,避免了res.render('home.html',...)的繁琐app.set('view engine', 'html');//路由挂载app.get('/', function(req, res) {//render函数除了用数据渲染页面之外,还有sendFile('home.html')的作用。res.render('home', {title: 'home',content: 'This is home page.'});});app.get('/article', function(req, res) {res.render('article', {title: 'article',content: 'This is acticle page.'});});//使用8080端口app.listen(8080);console.log("The server is running on 8080");
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title><%=title%></title></head><body><%=content%></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title><%=title%></title></head><body><%=content%></body></html>
node app.js
打开浏览器键入:localhost:8080 和 localhost:8080/article

源代码地址:https://github.com/kexinWeb/node-express-ejs-demo.git
本例子只是简单阐明node,express还有ejs之间的组织结构关系,更多的ejs语法可以参见 https://segmentfault.com/a/1190000004286562
参考资料:
【1】http://www.cnblogs.com/rubylouvre/p/3421805.html
【2】http://github.com/visionmedia/ejs
【3】https://segmentfault.com/a/1190000004286562