Express Handlebars 部分不做任何事情

Express Handlebars Sections don't do anything

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

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.车把

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

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

        {{{ body }}}

    </body>
</html>

views/home.车把

{{#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>

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

真正的问题是:在定义 Handlebars Helper 时不要使用 arrow functions

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

所以真正的修复应该是:

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 post 了解更多信息:

  • Can't access array element after calling helper (Handlebars)

Also, you have a typo on your CSS:

h1 { color: "red" }

Is not correct; The color datatype doesn't include quotes. So the correct CSS should be

h1 { color: red }