Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use helpers in handlebars with webpack(handlebars-loader)

I am using Handlebars in my project and bundling templates using webpack. I am using handlebars-loader to compile templates. I got issue when I created a small helper. Webpack shows this error when I use helper in my template:

You specified knownHelpersOnly, but used the unknown helper withCurrentItem - 5:4

This is my code:

Webapck:

{
        test   : /\.(tpl|hbs)$/,
        loader : "handlebars-loader?helperDirs[]=" + __dirname + "templates/helpers"
        // use    : 'handlebars-loader?helperDirs[]=false' + __dirname + 'templates/helpers'
},

Helper(project/templates/helpers/withCurrentItem.js):

export default function (context, options) {
  const contextWithCurrentItem = context

  contextWithCurrentItem.currentItem = options.hash.currentItem

  return options.fn(contextWithCurrentItem)
}

Template file(project/templates/products.tpl):

{{> partials/filters}}
<ul class="u-4-5">
  {{#each data.products}}
    {{> partials/product}}
    {{withCurrentItem ../styles currentItem=this}}
  {{/each}}
</ul>

I tried to resolve the problem and searched over the internet but I couldn't find any thing. This is what I have tried to:

  • Add helperDirs[] query param to loader as:

    loader : "handlebars-loader?helperDirs[]=" + __dirname + "templates/helpers"

  • Add helpers directory path to resolve.modules property of webpack config file

Sadly, none of them work.

like image 432
Bharat Soni Avatar asked Jun 14 '17 11:06

Bharat Soni


1 Answers

For me, none of these approaches worked. I used runtime option to create my own instance of Handlebars (thanks to this comment):

webpack.config.js

module: {
  rules: [
    {
      test: /\.(handlebars|hbs)$/,
      loader: 'handlebars-loader',
      options: {
        runtime: path.resolve(__dirname, 'path/to/handlebars'),
      },
    },

path/to/handlebars.js

const Handlebars = require('handlebars/runtime');
Handlebars.registerHelper('loud', function(aString) {
  return aString.toUpperCase();
});
module.exports = Handlebars;
like image 60
Vahid Avatar answered Sep 28 '22 12:09

Vahid