【问题标题】:Express Handlebars Sections don't do anythingExpress Handlebars 部分不做任何事情
【发布时间】:2020-10-10 21:42:40
【问题描述】:

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

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}`);
});

视图/布局/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。

可能出了什么问题?

【问题讨论】:

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


    【解决方案1】:

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

    真正的问题是:在定义 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 帖子:

    另外,你的 CSS 有错字:

    h1 { color: "red" }
    

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

    h1 { color: red }
    

    【讨论】:

      【解决方案2】:

      如果您在源 html 的头部声明样式,它会起作用。

      views/home.handlebars 应该是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多