node-steam-guide
node-steam-guide copied to clipboard
Issue with express-handlebars (Error: ENOENT: no such file or directory, open '..\views\layouts\main.handlebars')
I get this error:
Error: ENOENT: no such file or directory, open '..\views\layouts\main.handlebars'
Whenever I add this code:
const express = require('express');
const handlebars = require('express-handlebars');
const path = require('path');
const app = express();
const hbs = handlebars.create();
app.engine('hbs', hbs.engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('main', {
title: 'Hey There, World!',
message: 'This is a fantastic example of Handlebars!'
});
});
app.listen(3037);
This is from chapter 4.
In your project folder, you should (for now) have a javascript file and a 'views' folder. Inside the views folder, create a file called 'main.hbs'. Also, create a directory called 'layouts'. inside the 'layouts' directory, create a file called 'steam-layout.hbs' for example.
leave the 'main.hbs' file empty. the 'steam-layout.hbs' file should contain:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Page: {{title}} </h1>
Message: {{message}}
</body>
</html>
Notice that we need to include the variables {{title}} and {{message}}
now change your js-code to:
const express = require('express');
const handlebars = require('express-handlebars');
const path = require('path');
const app = express();
app.set("view engine", "hbs");
app.engine(
"hbs",
handlebars({
layoutsDir: __dirname + "/views/layouts",
extname: "hbs",
})
);
app.get("/", (req, res) => {
res.render("main", {
layout: "steam-layout",
title: "Hey There, World!",
message: "This is a fantastic example of Handlebars!",
});
});
app.listen(3037);
I'm also new to handlebars but there are some great guides that explain the concept of views, layouts, and partials in detail. check out: https://bit.ly/37sqYsu