在Express中安装XTemplate

上一节讲了安装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, 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.

app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); })

其链接为:http://expressjs.com/advanced/developing-template-engines.html

也就是说要配置xptl的renderFile函数才行,不过为什么不用配置是可以的,后续还要看下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值