nodejs中使用velocity
程序员文章站
2022-06-29 18:25:35
...
学习nodejs框架发现都是jade,不复杂,也不想学,如果会velocity就不用再学jade了。
可以直接在nodejs中使用velocity,因为npm里有velocityjs。
用express建一个项目[quote]express demo[/quote]目录如下:
稍改app.js就行
可以直接在nodejs中使用velocity,因为npm里有velocityjs。
用express建一个项目[quote]express demo[/quote]目录如下:
│ app.js //node app.js 启动
│ package.json
│
├─public
│ ├─css
│ ├─img
│ └─js
├─routes
│ index.js
│ user.js
└─views //vm模板
footer.vm
head.vm
index.vm
mainBody.vm
改package.json(默认是jade,其实不改也没关系){
"name": "cjx",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.3",
"jade": "*",
"velocityjs":"0.4.2"
}
}
稍改app.js就行
/**
* Module dependencies.
*/
var express = require('express') //express
var velocity = require('velocityjs') //velocityjs
var routes = require('./routes')
var user = require('./routes/user')
var http = require('http') //
var fs = require('fs') //
var path = require('path') //
var routes = require('./routes') //
var app = express() //app
var cwd = process.cwd() //cwd
console.log("cwd="+cwd);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'vm');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
//全用vm模板引擎
app.engine('vm',function(path,options,fn){
var template = fs.readFileSync(path).toString();
var macros = {
parse: function(file) {
var template = fs.readFileSync(cwd + '/views/' + file).toString()
return this.eval(template);
}
}
try{
fn(null, velocity.render(template, options, macros))
}catch(err){
console.log(err);
fn(err)
}
});//end engine
app.use(express.static(cwd+"/public"));
app.use(express.logger());
app.get('/index', routes.index);
//设端口
var port = process.argv[2];
port = /^\d{4,5}$/.test(port) ? port :app.get('port');
console.log('Listening on', port);
http.createServer(app).listen(port, function(){
console.log('Server listening on port ' + port);
}).on('error',function(err){
console.log('错了',err.code);
});
上一篇: 护士专科学校的期中考试