Express Handlebars Sections不执行任何操作

问题描述

我目前正在尝试使用快捷把手在我的网站中实现部分。我的代码如下:

index.js

const path = require("path");
const express = require("express");
const expressHandlebars = require("express-handlebars");

const app = express();
app.engine("handlebars",expressHandlebars({
    defaultLayout: "main",helpers: {
        section: (name,options) => {
            if (!this._sections) {
                this._sections = {};
            }
            this._sections[name] = options.fn(this);
            return null;
        }
    }
 }));
app.set("view engine","handlebars");
app.use(express.static("public"));

app.get("/",(req,res) => {
    res.render("home",{ title: "Home" });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
    console.log(`Listening on port ${PORT}`);
});

views / layouts / main.handlebars

<!DOCTYPE html>
<html lang="en">
    <head>
        <Meta charset="utf-8">
        <title>{{{ title }}}</title>

        {{{_sections.head}}}
    </head>
    <body>

        {{{ body }}}

    </body>
</html>

views / home.handlebars

{{#section "head"}}
<style>
    h1 {
        color: "red";
    }
</style>
{{/section}}

<h1>test</h1>

预期结果:

它正确显示带有文本“ test”的h1标签。但是,由于{{#section "head"}}标题应为红色,但应为黑色。

我已经正确安装了express和expressHandlebars。

有什么问题吗?

解决方法

如果您在源html的头部声明样式,则该方法有效。

views / home.handlebars 应该显示为:

<head>
    <style>
        h1 {
            color: red;
            border: solid 1px green;
        }
    </style>
</head>

<h1>test</h1>
,

以上答案实际上并未解决您的问题。

真正的问题是:在定义车把助手时不要使用arrow functions

因此,助手中的this设置不正确,因此rendering it our via options.fn(this)不起作用。

因此 real 修复应为:

app.engine(
    'handlebars',expressHandlebars({
        defaultLayout: 'main',helpers: {
            // ? Importantly,define the helper as a regular `function`,_not_ an arrow-function.
            section(name,options) {
                if (!this._sections) {
                    this._sections = {};
                }
                this._sections[name] = options.fn(this);
                return null;
            },},})
);

有关此方面的更多信息,请参见下面的SO帖子:

此外,您在CSS上有错字:

h1 { color: "red" }

不正确; color数据类型不包含引号。因此正确的CSS应该是

h1 { color: red }