javascripthandlebars.js

How to set layout's page title from a view?


Let's say I have this Handlebars layout:

<!DOCTYPE html>
<html>
    <head>
        <title>Page title</title>
    </head>
    <body>
        <div>
            {{{body}}}
        </div>
    </body>
</html>

How can I set the title from the actual view or page ?


Solution

  • I did it with the block and content helpers from handlebars-layout package.

    In the layout:

    <!DOCTYPE html>
    <html>
        <head>
           {{#block "header"}}
             <title>Page title</title>
           {{/block}}
        </head>
        <body>
            <div>
                {{{body}}}
            </div>
        </body>
    </html>
    

    Then in the view:

    {{#content "header"}}
       <title>My specific title</title>
    {{/content}}
    

    The app setup is as follow:

    import express from 'express';
    import { create } from 'express-handlebars';
    import layouts from 'handlebars-layouts';
    
    
    const app = express();
    
    // View engine setup
    const hbs = create({ extname: '.hbs' });
    layouts.register(hbs.handlebars);
    app.engine('.hbs', hbs.engine);
    app.set('view engine', '.hbs');
    app.set('views','./views');
    
    // Endpoints
    app.get('/', (req, res) => {
        res.render('home', {});
    });
    
    app.listen(process.env.PORT, () => console.log('Running'));