在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函數才行,不過爲何不用配置是能夠的,後續還要看下

相關文章
相關標籤/搜索