How to change default layout in express using handlebars?

前端 未结 5 1108
清歌不尽
清歌不尽 2020-12-07 11:30

I am using Express 4.9.0 and express-generator.

Created boilerplate with a following command:

express --hbs projectname

Builtin han

5条回答
  •  不思量自难忘°
    2020-12-07 11:36

    If you're using the 'express-handlebars' module, then the following should work:

    // ...
    app.set("views", __dirname );
    
    exphbs.ExpressHandlebars.prototype.layoutsDir = 'path/to/directory/';
    app.engine('handlebars', exphbs({defaultView: 'name-of-template'}));
    
    // ...
    

    I came to this by digging around in the module's source, it turns out that this line...

    // express-handlebars/lib/express-handlebars.js (line 55 in v1.2.2)
    ExpressHandlebars.prototype.layoutsDir  = 'views/layouts/';
    

    ...is what gives the default behaviour of always looking in '{{whatever you specified}}/views/layouts/'

    So essentially - if, perhaps, you have a different dir structure in mind or have some other reason to override it, you can by using the line in my example. Just be sure that you do this before you instantiate exphbs.

    If you're using some other module (I'm not sure which are out there) it's likely that they have some similar setting that can be overridden with a bit of jiggery-pokery (just run a 'find' on the file contents for 'views/layouts/'.

    note that I am leaving 'app.set("views", __dirname );' as is so that I keep templates anywhere in my server directory and render them like so:

    res.render("moduleName/templateName");
    

    After updating to v2.0.1 The above won't work, instead you can pass the default directory in as an argument as below:

    var hbs = exphbs.create({
      layoutsDir: 'app/server/',
      ...
    

提交回复
热议问题