nodejs+Express中使用mustache模板引擎

由于公司一个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);

猜你喜欢

转载自www.cnblogs.com/liyan-web/p/9025860.html