如何在 express 中重用带有车把的布局?

How do I reuse my layout with handlebars in express?

好吧,我不想在每个视图中都包含我的实际布局。

所以我的观点看起来像

layout.hbs

<html lang="en">
<head></head>
<body>
<div id="content">
    {{ content }}
</div>
</body>
</html>

index.hbs

<div>my index content</div>

help.hbs

<div>my help content</div>

当我像下面的例子那样使用我的快速路线时,我只需要在每个视图中包含我的整个布局——这显然是个坏主意。

快速路线

app.use('/', function (req, res) {
    res.render('index', {content: 'foo'});
});
app.use('/about', function (req, res) {
    res.render('about', {content: 'foo'});
});

所以问题是:如何在车把视图中重用我的布局?

我的想法是像

那样额外编译我的内容
app.use('/', function (req:express.Request, res:express.Response, next:Function) {
    fs.readFile(path.join(viewPath, 'index.hbs'), function(err, text){
        var template = hbs.handlebars.compile(text);
        var content = template({foo: 1234});
        res.render('layout', {content: content}); 
    }); 
});

但我不确定这是否正确。

您可以使用 express-handlebars 并为其设置默认布局。

var hbs = exphbs.create({
    extname:'hbs',
    layoutsDir:  '/path/to/layouts',
    defaultLayout: 'main'
});

// Initialize engine
app.engine('hbs', hbs.engine);

// Set engine
app.set('view engine', 'hbs');

设置布局后,您只需调用res.render({content: content});