Search code examples
node.jsexpress-handlebarsregisterhelper

Where to put Handlebars.registerHelper function in node.js project?


I want to increase "totalPrice" by 10 and then display it in handlebars templates . Here z some snippet of my handlebar file. checkout.hbs

<ul class="shipping__method">
       <li>Shipping <span>$ 10</span></li>
 </ul>
 <ul class="total__amount">
   <li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>

For that i write this in my app.js file

  var expressHbs =  require('express-handlebars');
    app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
     app.set('view engine', '.hbs');
    expressHbs.registerHelper ('increasePrice', function (price) {
      price+=10;
      return price;
     })

And then i got error expressHbs.registerHelper is not a function. Then i came to know to write it like this

 var hbs = expressHbs.create({
 helpers: {
   increasePrice: function(price) {
     price+=20;
     return price;
   }
  }
})

And then i got error like "missing Helper: "increasePrice" ".


Solution

  • 👨‍🏫 You see this code below 👇, an example code using express and express-handlebars:

    index.js

    var express = require('express');
    
    var app = express();
    
    var expressHbs =  require('express-handlebars');
    
    app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
    app.set('view engine', '.hbs');
    
    var hbs = expressHbs.create({});
    
    // register new function
    hbs.handlebars.registerHelper('increasePrice', function(price) {
      price+=10;
      return price;
    })
    
    app.get('/', (req, res) => {
      res.render('home', {
        layout: false,
        totalPrice: 300,
      });
    })
    
    app.listen(3000, () => {
      console.log('Server is up');
    });
    

    Now create file home.hbs in views, and put this code below 👇 in there.

    home.hbs

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>My Example APP</title>
    </head>
    
    <body>
    
      <ul class="shipping__method">
        <li>Shipping: Total Price <span>$ {{ totalPrice }}</span></li>
      </ul>
      <ul class="total__amount">
        <li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
      </ul>
    </body>
    </html>
    

    From the code above 👆, I hope you can understand now, where you have to put your function.

    For an example: You can see on my codesandbox

    I hope it's can help you 🙏.