上一节讲了安装Express,并且生成了一个"microblog"的工程,我们的目标是在工程下安装XTemplate:
1.安装xtpl
npm install xtpl xtemplate --save
2.在views目录添加test.xtpl文件,其内容为
this is {{title}}!
3.可以做一个简单的测试,判断xtpl是否安装成功
var xtpl = require('xtpl');
xtpl.renderFile('./views/test.xtpl',{
title:'Express'
},function(error,content){
console.log(content);
});
输出:this is Express!
4.集成到Express中,只需要在app.js中,设置模板引擎即可
app.set('view engine', 'xtpl');
5.测试一个路径
var print = require('./routes/print');
app.use('/ooxx', print);
在print.js中
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('test', { title: 'Express' });
});
module.exports = router;
6.此时如果在浏览器输入:127.0.0.1:3000/ooxx
显示为:this is Express!
需要注意的是,如果要自定义Express的模板引擎,是需要
Use the app.engine(ext, callback)
method to create your own template engine. ext
refers to the file extension, callback
is the template engine function which accepts the location of the file, the options object, and the callback function, as its parameters.
The following is an example of implementing a very simple template engine for rendering ".ntl" files.
var fs = require('fs'); // this engine requires the fs module
app.engine('ntl', function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
if (err) throw new Error(err);
// this is an exteremly simple template engine
var rendered = content.toString().replace('#title#', '<title>'+ options.title +'</title>')
.replace('#message#', '<h1>'+ options.message +'</h1>');
return callback(null, rendered);
})
});
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine
Your app will now be able to render ".ntl" files. Create a file named "index.ntl" in the views directory with the following content.
#title#
#message#
Then, create the following route in your app.
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
})
其链接为:http://expressjs.com/advanced/developing-template-engines.html
也就是说要配置xptl的renderFile函数才行,不过为什么不用配置是可以的,后续还要看下