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?
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.
if you want use express-handlebars
and register helpers for .hbs
template you can following my answered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.