grunt-contrib-handlebars - Output is different tha

2019-05-11 21:47发布

问题:

Thank you in advance for your time and help.

I'm trying to precompile handlebars (.hbs) templates using grunt-contrib-handlebars

When I run the run task I end up with this:

this["JST"] = this["JST"] || {};

this["JST"]["app/templates/err.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


  buffer += "<div>Error: ";
  if (stack1 = helpers.error) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.error; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "</div>";
  return buffer;
  });

However, if I run the npm handlebars module from terminal I get this:

(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['err.hbs'] = template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


 buffer += "<div>Error: ";
 if (stack1 = helpers.error) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
 else { stack1 = depth0.error; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
 buffer += escapeExpression(stack1)
   + "</div>";
 return buffer;
 });
})();

The second compiled template (run from terminal) works correctly in my app - but the one that grunt creates does not. Could someone perhaps point me in the right direction with what I might be doing wrong here?

My gruntfile looks like this:

handlebars:
       options:
                wrapped: true
       compile:
                files: 'www/js/templates.js': ['app/templates/*.hbs']

Thanks again for your help!

回答1:

Turns out this was a problem caused by using different versions of Handlebars where the grunt-contrib-handlebars version was different then the globally installed handlebars npm module.



回答2:

You could also use a function as "processName" and specify a "namespace" in Gruntfile, for example something like this if you have only one file article_snippet.handlebars in a single folder called handlebars could do the job:

    handlebars: {
      compile: {
        options: {
          namespace: 'Handlebars.templates',
          processName: function(filename) {
              var name = filenaname.split('/')[1].split('.');
              return name[0];
          },
          wrapped: true,
          commonjs: null
        },
        files: {
          "js/articles/templates.js": "handlebars/article_snippet.handlebars",
        }
      }
    },

taking inspiration from grunt-contrib-handlebars doc