Search code examples
javascriptjquerynode.jshandlebars.js

Template in template Handlebars


I am developing a NodeJs app, with express and handlebars. What I want is that I can reuse some partials like the header and footer elements.

So I thought, I pick the 'base' html. And shoot the required html elements in it via Handlebars.

I have this at my index.js:

const functions = require('firebase-functions');
const express = require('express');
const engines = require('consolidate');

const app = express();
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');

app.get('/activiteiten', (request, response) => {

    // var test = require('./views/dayCard.hbs');
    // var data = {display_name: "hi"};
    // var theCompiledHtml = test(data);

    response.render('index', {
        menu_item: "Mijn Dashboard",
        menu_sub: "Activiteiten"
        //content: theCompiledHtml

    });
});


exports.app = functions.https.onRequest(app);

This works like expected. But I want to append some more data to it. So I have created the content tag in the template. Besides that, I have added the html to the dayCard.hbs.

Daycard.hbs:

<div class="col-xs-12 col-md-6 col-lg-3">
    <div class="card-deck text-center">
        <div class="card box-shadow">
            <div class="card-header">
                <h4 class="my-0 font-weight-normal">{{display_name}}</h4>
            </div>

            <div class="card-body">
            </div>
        </div>
    </div>
</div>

I want to use that file, append some data to it. And append that total package to the content tag. So a sort of template into a template. How can I do that?


Solution

  • If you are going to have more than one partial you should probably set up a structure like so

    - views
      - layouts
          layout.hbs //your html boilerplate layout
      - partials
          header.hbs
          footer.hbs
      index.hbs 
    

    In index.js set your view engine with default layout.

        // View Engine
        app.set('views', path.join(__dirname, 'views'));
        app.engine('handlebars', expressHandlebars({ defaultLayout: 'layout' }));
        app.set('view engine', 'handlebars');
    

    Then in your layout.hbs file you can use the partial syntax e.g. for Daycard.hbs {{> Daycard}}

       <!DOCTYPE html>
         <html>
         <head></head>
           <body>
             {{> navbar}}
             {{{body}}}  //which will render the contents of index.hbs
             {{> footer}}
           </body>
        </html>