0

I can't make the section helper work as intended. The body of login.hbs was parsed normally, but the js section was never parsed. I have tried using helpers inside res.render() and put section() straight into engine() and it didn't work either

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"));

main.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}}

Edit

I can't embed HTML either

login.hbs

<h1>Hello</h1>

{{#section "js"}}
<p>a paragraph</p>
{{/section}}
vca_bars
  • 11
  • 1

1 Answers1

0

I tried to run it. The real reason why it is not rendering is because inside your main.hbs you need to have {{{_sections.js}}} inside the html body tags instead of just {{{_section.js}}} like you have it now. The script tag should run as well.

Sorry for the confusion with the previous answer.

Esszed
  • 597
  • 1
  • 3
  • 15