express-handlebars icon indicating copy to clipboard operation
express-handlebars copied to clipboard

Unable to set default directory for views

Open max-fabertech opened this issue 11 years ago • 5 comments

Hello, I am unable to set default views directory.

OS: Ubuntu 15.04 Node: 4.0.0

I am in app directory (...). When running node server/server.js, it ignores app.set('views', path.join(__dirname, 'views')); from server.js and tries to load .../views/layouts/main.handlebars instead .../server/views/layouts/main.handlebars

.
└── server
    ├── server.js
    └── views
        ├── home.handlebars
        └── layouts
            └── main.handlebars

server.js

'use strict';

var path = require('path');
var express = require('express');
var exphbs  = require('express-handlebars');
var app = express();

// Rendering engine setup
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, 'views'));
console.log(path.join(__dirname, 'views'));

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

app.listen(8888);

EDIT: it works when i am in (.../server/ directory) and node server.js, it is wierd, becouse it should get right path from app.locals.setting.views variable.

max-fabertech avatar Sep 27 '15 19:09 max-fabertech

@camabeh - path.join(__dirname, 'views')) searches for server/views/<your-file-here>. But the views are not inside server folder. Update the path of views to use the correct path. app.set('views', __dirname + '/../views');

swarajgiri avatar Sep 28 '15 04:09 swarajgiri

@swarajgiri I don't get it. I think it should respect app.locals.settings.views and set layouts/ and partials/ relative to new views path. It looked in project's root folder for views/partials and views/layouts

Here I fixed it. https://github.com/ericf/express-handlebars/pull/148

max-fabertech avatar Sep 28 '15 07:09 max-fabertech

@camabeh - I have exactly the same issue. I modified (temporary) the code in the library according to your PR changes and confirm that it solves the problem. Until your PR is merged I choose to set layoutsDir and partialsDir in engine factory:

app.set('views', config.root + '/server/views');

var exphbs = require('express-handlebars');
app.engine('.hbs', exphbs({
        defaultLayout: 'main', 
        extname: '.hbs',
        layoutsDir:'server/views/layouts',
        partialsDir:'server/views/partials'
}));
app.set('view engine', '.hbs');

lmaran avatar Nov 25 '15 21:11 lmaran

I have a problem: "Error: The partial header could not be found....."

does anyone know how to solve it?

NBThiet avatar Sep 12 '21 15:09 NBThiet

Thanks Bro for this!!

nathandelgado-dev avatar Jan 10 '22 20:01 nathandelgado-dev