nodejs+Express中使用mustache模板引擎
阿新 • • 發佈:2018-05-11
後端 hello 簡單 set 一次 view index %s 安裝
由於公司一個seo項目,需要我協助。此項目他人已經開發大半,由於seo需要,使用了服務器端模板引擎。
我項目的後端同事說項目是go語音寫的,跑項目麻煩,只給了我template和css等靜態文件。
為了方便自己調試模板花了點時間用nodejs跑了一套。
裝node就不說了,網上很多
mkdir appName cd appName/ npm init npm install express --save npm install mustache --save npm install mustache-express --save //網上有的是用stache,不過看其註冊模板引擎用的是app.register()應該是以前的了,我試了用不了後來找到了這個mustache-express
只是為了方便調試,目錄結構比較隨意
不廢話,直接上代碼,app.js:
var express = require(‘express‘); var rf = require("fs"); var mustacheExpress = require(‘mustache-express‘); var app = express(); app.use(‘/static‘, express.static(‘static‘));//靜態文件托管 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文檔現在 是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) {//讀取自己寫的模擬數據 if (err) { console.log("error"); } else { data = JSON.parse(data); data.LanguageDisplay = "zh-hans"; res.render(‘index‘, data);//把讀取的數據填充進模板 } }); }); 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
現在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);
nodejs+Express中使用mustache模板引擎