nodejs+Express中使用mustache模板引擎
生活随笔
收集整理的這篇文章主要介紹了
nodejs+Express中使用mustache模板引擎
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
由于公司一個seo項目,需要我協(xié)助。此項目他人已經(jīng)開發(fā)大半,由于seo需要,使用了服務(wù)器端模板引擎。
我項目的后端同事說項目是go語音寫的,跑項目麻煩,只給了我template和css等靜態(tài)文件。
為了方便自己調(diào)試模板花了點時間用nodejs跑了一套。
裝node就不說了,網(wǎng)上很多
mkdir appName
cd appName/
npm init
npm install express --save
npm install mustache --save
npm install mustache-express --save
//網(wǎng)上有的是用stache,不過看其注冊模板引擎用的是app.register()應(yīng)該是以前的了,我試了用不了后來找到了這個mustache-express
只是為了方便調(diào)試,目錄結(jié)構(gòu)比較隨意
不廢話,直接上代碼,app.js:
var express = require('express');
var rf = require("fs");
var mustacheExpress = require('mustache-express');
var app = express();
app.use('/static', express.static('static'));//靜態(tài)文件托管
app.engine("mustache", mustacheExpress());//npm 安裝的mustache沒有提供模板引擎,不注冊模板引擎會報錯Error: Module "mustache" does not provide a view engine.
app.set('views', './templates/zh-hans/');
app.set('view engine', 'mustache');
// app.register(".mustache", require('stache'));
//第一次找到的是上面這句代碼,但api更換了報錯。查看api文檔現(xiàn)在 是app.engine
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.get('/zh-hans', function(req, res) {
rf.readFile("./mock/index.js", 'utf-8', function(err, data) {//讀取自己寫的模擬數(shù)據(jù)
if (err) {
console.log("error");
} else {
data = JSON.parse(data);
data.LanguageDisplay = "zh-hans";
res.render('index', data);//把讀取的數(shù)據(jù)填充進模板
}
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
然后
node app.js
現(xiàn)在http://localhost:3000/zh-hans/就可以訪問了
是不是很簡單
使用模板引擎的的代碼就5句
var mustacheExpress = require('mustache-express');
app.engine("mustache", mustacheExpress());
app.set('views', './templates/zh-hans/');
app.set('view engine', 'mustache');
res.render('index', data);
總結(jié)
以上是生活随笔為你收集整理的nodejs+Express中使用mustache模板引擎的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第三课 Hello World显示
- 下一篇: EQ 均衡器