Kannan J
Kannan J

Reputation: 508

How to load array of handlebar templates through web pack?

Is there a way to compile directory of templates and store in array object using Webpack?

Explanation: I am now using list of handlebars templates. I precompile the list of templates using handlebars compiler in gulp.

gulp.src('client/src/templates/**/*.hbs')
  .pipe(gulp_handlebars({
      handlebars: handlebars,
       compilerOptions:{
        knownHelpers: helpers,
        knownHelpersOnly:true}
      }))
      .pipe(wrap('Handlebars.template(<%= contents %>)'))
      .pipe(declare({
        namespace: 'appname.templates',
        noRedeclare: true, 
        processName: function(filePath) {
          return declare.processNameByPath(filePath.replace('client/src/templates/', ''));
        }
      }));

I would then access templates through appname.templates array. It was working fine.

Now, I am moving to Webpack. If I use the handlebars-loader , it allows me to require every template by name like

var template = require("./file.handlebars");

Is there a way to get all templates in one directory as an array like

var templates = require("./*.handlebars");

Upvotes: 2

Views: 559

Answers (1)

albertfdp
albertfdp

Reputation: 427

I usually would go to the folder you have your templates and have an templates/index.js file such as:

export templateA from './templateA.handlebars'
export templateB from './templateB.handlebars'
export templateC from './templateC.handlebars'
...

Then you can do:

import * as templates from './templates'

And templates is an object that holds all your templates. You can also do templates.templateA to access them by name.

Upvotes: 2

Related Questions