How to change default layout in express using handlebars?

前端 未结 5 1101
清歌不尽
清歌不尽 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:38

    From the handlebars readme:

    There are two ways to set a default layout: configuring the view engine's defaultLayout property, or setting Express locals app.locals.layout.

    The layout into which a view should be rendered can be overridden per-request by assigning a different value to the layout request local. The following will render the "home" view with no layout:

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

    In case you want to set the default layout just for a specific subroute, you might wanna use the following in the top section of your route:

    router.all('/*', function (req, res, next) {
        req.app.locals.layout = 'admin'; // set your layout here
        next(); // pass control to the next handler
        });
    

    You can also set the default layout on initialization:

    // Create `ExpressHandlebars` instance with a default layout.
    var hbs = exphbs.create({
        defaultLayout: 'main',
        helpers      : helpers,
    
        // Uses multiple partials dirs, templates in "shared/templates/" are shared
        // with the client-side of the app (see below).
        partialsDir: [
            'shared/templates/',
            'views/partials/'
            ]
        });
    
    // Register `hbs` as our view engine using its bound `engine()` function.
    app.engine('handlebars', hbs.engine);
    app.set('view engine', 'handlebars');
    

提交回复
热议问题