【问题标题】:How can I use Handlebars with Express?如何在 Express 中使用 Handlebars?
【发布时间】:2018-08-05 17:39:50
【问题描述】:

这个问题其实不难理解,不知道如何在Express中实现handlebars。

这是我已经编码的:

var express = require('express');
var app = express();

app.get('/', function (req, res, next) {
        return res.render('index');
});

现在我的问题是,如何将车把设置为 Express 的应用引擎?

【问题讨论】:

  • [无耻插件] 如果您愿意尝试其他 Web 框架,您应该尝试zox.js,它有一个内置的车把引擎,所以您不必自己设置。 [/无耻塞]

标签: javascript node.js express handlebars.js express-handlebars


【解决方案1】:

这是我目前使用和学习的代码。我在每条重要的行后面都加了注释,方便大家理解!

var express = require('express');
var app = express();
var handlebars = require('express-handlebars');

app.engine('handlebars', handlebars({ // Here we define what format you will use (That means what's at the end of each file, for example test.handlebars or test.hbs)
    defaultLayout: 'main', // That's the name of your template file. In my case it's main.handlebars
    layoutsDir: __dirname + '/views/layouts/' // That's the directory where the template file is
}));

app.set('views', path.join(__dirname, 'views')); // Here you give express the information that it has to look at all files that are in the path /views
app.set('view engine', 'handlebars'); // Here you say express that you are using handlebars to build your website

app.get('/home', function (req, res, next) { // That's a simple GET request (This GET request gets triggered when you enter http://localhost/home for example)
        return res.render('index');  // Here we render the index.handlebars file (that is in the /views folder)
});

【讨论】:

    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2019-03-23
    • 2014-10-11
    • 1970-01-01
    • 2019-10-17
    • 2013-07-16
    相关资源
    最近更新 更多