Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register custom Handlebars helpers?

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?

like image 310
BenAdamson Avatar asked Jan 20 '17 13:01

BenAdamson


People also ask

How do I register Handlebars in helpers?

registerHelper("noop", function(options) { return options. fn(this); }); Handlebars always invokes helpers with the current context as this , so you can invoke the block with this to evaluate the block in the current context.

Which function is use for creating custom helpers in Handlebars?

We can create our own helper functions in Handlebars using the registerHelper() method.

What is helper in Handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}

How do you add Handlebars in HTML?

Options to Include Handlebars JavaScriptInline inclusion inside HTML page with “<script id="template-id" type="text/x-handlebars-template">Define template</script>”. Create external template, using the “. handlebars” extension.


1 Answers

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.

like image 103
Titus Sutio Fanpula Avatar answered Sep 18 '22 13:09

Titus Sutio Fanpula