在Express中安装XTemplate

上一节讲了安装Express,而且生成了一个"microblog"的工程,咱们的目标是在工程下安装XTemplate:javascript

1.安装xtplhtml

npm install xtpl xtemplate --save java

2.在views目录添加test.xtpl文件,其内容为express

this is {{title}}!npm

3.能够作一个简单的测试,判断xtpl是否安装成功浏览器

var xtpl = require('xtpl');
xtpl.renderFile('./views/test.xtpl',{
title:'Express'
},function(error,content){
console.log(content);
});app

输出:this is Express!函数

4.集成到Express中,只须要在app.js中,设置模板引擎便可测试

app.set('view engine', 'xtpl');ui

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, callbackis 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.


其连接为:http://expressjs.com/advanced/developing-template-engines.htmlapp.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); })

也就是说要配置xptl的renderFile函数才行,不过为何不用配置是能够的,后续还要看下

相关文章
相关标签/搜索