Dovahkiin
Dovahkiin

Reputation: 65

Error: Failed to lookup view "home.hbs" in views directory

I am implementing a web app with a three layered architecture. Now I am trying to render a file in my views folder. This is my folder structure and the code:

enter image description here

But when I run this, I get the following error:

Error: Failed to lookup view "home.hbs" in views directory "/web-app/pl/views"

Any suggestions how to make this work?

Upvotes: 0

Views: 1277

Answers (1)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

💡 Your bug is in this code app.set('views', path.join("/web-app/pl", "views")); make sure to remove / in your /web-app. So its will looks like this app.set('views', path.join("web-app/pl", "views"));

👨‍🏫 Make sure to create a folder in your root app: web-app/pl/views And put your home.hbs in your views folder.

So your folder will looks like this: 👇

- public
- node-modules
- src > server.js
- web-app > pl > views > home.hbs // if set in render { layout: false }
- web-app > pl > views > layouts > main.hbs // default layout

👨‍🏫 For an example, your app will looks like this code below: 👇

const express = require('express');
const expressHandlebars = require('express-handlebars');
const path = require('path');

const app = express();

app.set('views', path.join("web-app/pl", "views"));
app.engine("hbs", expressHandlebars({
  defaultLayout: "main.hbs"
}))

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

app.use(express.static('public'));

app.get('/', function (req, res) {
  res.render('home', {
    layout: false
  })
});

app.listen(3000, () => {
  console.log('Server is up');
})

For an example you can see in my codesandbox: https://codesandbox.io/s/strange-darkness-73opp

I hope it can help you 🙏.

Upvotes: 1

Related Questions