How to register custom Handlebars helpers?
27,382
For an example, you can see the code below:
var express = require('express');
var app = express();
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}).engine)
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');
});
The code above only an example.
You can see an example on this site: https://codesandbox.io/s/elegant-fog-1n61o
I hope it can help you.
Author by
BenAdamson
Electronic Engineer BEng Electronic & Communications Engineering (Hons) MIET Experience in defence avionics & space (satellite) industries.
Updated on July 01, 2022Comments
-
BenAdamson almost 2 years
After a long search I still can't seem to find much information on where to put my custom handlebars helpers. Do I put them in a
<script>
in my webpage's .hbs file? Do I put them in app.js? Do I put them in the page's router?Here's the helper I'd like to register by the way:
Handlebars.registerHelper("last", function(array) { return array[array.length - 1]; });
I'm assuming once I've put that code somewhere I can just use it on any page by using
{{last foo}}
, right?