Home > Enterprise >  How to set views path in express-handlebars?
How to set views path in express-handlebars?

Time:04-02

I'm trying to change where handlebars looks for my file 'index.hbs' but when I try to render it returns this error:
Error: Failed to lookup view "index" in views directory ".../views"
I think that error means handlebars is looking for my file in the folder ".../views" but I have it stored in ".../src/views" so I wrote in the file server.js this line: app.set('views', path.join(__dirname, 'views')), which is suposed to change where handlebars looks for index.hbs but it doesn't. path.join(__dirname, 'views') returns ".../src/views" if I print it in console.

Project structure:
| src
| | views
| | | index.hbs
| | | partials
| | | layouts
| | | | main.hbs
| | routes.js
| | server.js

server.js

const express = require('express');
const app = express();
const path = require('path');
const xpshbs = require('express-handlebars');

// Settings
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', xpshbs({
  defaultLayout: 'main',
  layoutsDir: path.join(app.get('views'), 'layouts'),
  partialsDir: path.join(app.get('views'), 'partials'),
  extname: '.hbs'
}));
app.set('view engine', '.hbs');

// Routes
app.use(require('./routes'))


// Initializations
app.listen(app.get('port'), () => {
  console.log(`Server listening in port ${app.get('port')}`)
})

routes.js

const Router = require('express');
const router = Router();

router.get('/', (req, res) => {
  res.render('index');
})

module.exports = router;

CodePudding user response:

This line

app.set('views', path.join(__dirname, 'views'));

needs to go after these lines:

app.engine('.hbs', xpshbs({
  defaultLayout: 'main',
  layoutsDir: path.join(app.get('views'), 'layouts'),
  partialsDir: path.join(app.get('views'), 'partials'),
  extname: '.hbs'
}));
app.set('view engine', '.hbs');

You're telling your app to find files for an engine that hasn't been established yet.

CodePudding user response:

I believe the issue is due to how you are importing and initializing your Router.

If we look at the first two lines of routes.js, we see:

const Router = require('express');
const router = Router();

We are importing the top-level function exported from the express module and invoking it. This is exactly the same code we are executing in the first two lines of server.js, just with different variable names:

const express = require('express');
const app = express();

Our issue is that we are constructing a new express app in the routes.js file, albeit one that we are calling "Router". The correct way to initialize a Router is:

const express = require('express');
const router = express.Router();

Once we have done this, we should find that our express-handlebars configuration takes effect for our app and our views are looked-up in the configured directory.

  • Related