日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

nodejs+Express中使用mustache模板引擎

發(fā)布時(shí)間:2023/10/11 125 老码农
生活随笔 收集整理的這篇文章主要介紹了 nodejs+Express中使用mustache模板引擎 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

由于公司一個(gè)seo項(xiàng)目,需要我協(xié)助。此項(xiàng)目他人已經(jīng)開(kāi)發(fā)大半,由于seo需要,使用了服務(wù)器端模板引擎。
我項(xiàng)目的后端同事說(shuō)項(xiàng)目是go語(yǔ)音寫(xiě)的,跑項(xiàng)目麻煩,只給了我template和css等靜態(tài)文件。

為了方便自己調(diào)試模板花了點(diǎn)時(shí)間用nodejs跑了一套。

裝node就不說(shuō)了,網(wǎng)上很多

mkdir appName
cd appName/
npm init
npm install express --save
npm install mustache --save
npm install mustache-express --save
//網(wǎng)上有的是用stache,不過(guò)看其注冊(cè)模板引擎用的是app.register()應(yīng)該是以前的了,我試了用不了后來(lái)找到了這個(gè)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沒(méi)有提供模板引擎,不注冊(cè)模板引擎會(huì)報(bào)錯(cuò)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更換了報(bào)錯(cuò)。查看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) {//讀取自己寫(xiě)的模擬數(shù)據(jù)
if (err) {
console.log("error");
} else {
data = JSON.parse(data);
data.LanguageDisplay = "zh-hans";
res.render('index', data);//把讀取的數(shù)據(jù)填充進(jìn)模板 }
});
}); 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/就可以訪問(wèn)了

是不是很簡(jiǎn)單

使用模板引擎的的代碼就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模板引擎的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。