【问题标题】:Problem with express-handlebars section helpers快速车把部分助手的问题
【发布时间】:2022-01-09 21:20:14
【问题描述】:

我无法使部分助手按预期工作。 login.hbs 的主体被正常解析,但 js 部分从未被解析。我尝试在res.render() 中使用助手并将section() 直接放入engine(),但它也不起作用

app.js

import express from "express"
import expressHbs from "express-handlebars"

const app = express();

app.use(express.urlencoded({ extended:true }));

app.engine('hbs', expressHbs.engine({
    defaultLayout: 'main.hbs',
    helpers: {
        section(name, options) {
            if (!this._sections)
                this._sections = {};
            this._sections[name] = options.fn(this);
            return null;
        },
    },
}));

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

app.get("/", (req, res) => {
    res.render("login");
})

app.listen(3000, () => console.log("listening"));

ma​​in.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    {{{body}}}

    {{{_section.js}}}
</body>
</html>

login.hbs

<h1>Hello</h1>
{{#section "js"}}
<script>
    console.log("hello world")
</script>
{{/section}}

编辑

我也无法嵌入 HTML

login.hbs

<h1>Hello</h1>

{{#section "js"}}
<p>a paragraph</p>
{{/section}}

【问题讨论】:

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


    【解决方案1】:

    我试图运行它。它不呈现的真正原因是因为在 main.hbs 中,您需要在 html 正文标签中添加 {{{_sections.js}}} 而不是像现在这样的 {{{_section.js}}}。脚本标签也应该运行。

    很抱歉与之前的答案混淆。

    【讨论】:

    • “在体内调用 {{{_sections.js}}}”是什么意思?
    • 在 main.hbs 的 html body 标签内。你有 section.js 而不是 section.js 改变它,它应该可以工作
    猜你喜欢
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2019-01-05
    相关资源
    最近更新 更多