Giter Club home page Giter Club logo

grunt-contrib-handlebars's People

Contributors

alexindigo avatar bengladwell avatar cjbarth avatar cmtegner avatar cowboy avatar ctjhoa avatar davidshimjs avatar dependabot[bot] avatar eddhannay avatar erwanjegouzo avatar jamesplease avatar jinroh avatar jmorrell avatar jondum avatar joostory avatar lazd avatar mrjoelkemp avatar nicjansma avatar pdokas avatar phawk avatar radkodinev avatar rpocklin avatar saunders99999 avatar shama avatar sindresorhus avatar stephanebachelier avatar thanpolas avatar vladikoff avatar webstrap avatar xhmikosr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-contrib-handlebars's Issues

Do not merge all source files

Hello there!

In our project we have several handlebars source files and we need to precompile them one by one. I mean, we need to have as many compiled files as original ones.
As far as I can tell, this plugin only allows to store all precompiled templates in the same file.
Is there any configuration that allows for precompiling template files separately.

Thanks.

NPM dependency fetches handlebars 1.0.0-rc.3

For some reason in the package.json that comes when I use "npm install grunt-contrib-handlebars", the dependency looks like this:
"handlebars": "git://github.com/spikebrehm/handlebars.js.git#0687c7016c62122ab160a8683817a931b03354ad",

This points to an older version of a fork of handlebars.js... I would have expected to get an 1.0.x instead. I'm also not sure why the npm package.json differs from the one in the github repository...

Question/Suggestion: Adding namespace for Handlebars

Hello,

I'm building a 3th. party application and I don't want to have Handlebars in the main namespace, because a different version might be already in use by the customer. Thus, I have something like window.MyApp = { Handlebars: {}, Templates: {}, ....}.

Is there a way to provide a namespace for Handlebars using grunt-contrib-handlebars?
Right now the output looks like:

this["MyApp"]["Templates"]["some_template"] = Handlebars.template(
    function (Handlebars,depth0,helpers,partials,data) {...

Instead of 'MyApp.Handlebars':

this["MyApp"]["Templates"]["some_template"] = MyApp.Handlebars.template(
    function (Handlebars,depth0,helpers,partials,data) {...

Thanks!
claudio.

How to use processPartialName & processContent functions?

Hey,

My processPartialName and processContent functions don't seem to be getting called or used. Am I doing something incorrectly?

        handlebars: {
            compile: {
                files: {
                    "assets/js/views.js":
                    "assets/js/view/*.mustache"
                },
                options: {
                    namespace: "App.views",
                    processPartialName: function(filePath) {
                      var segments = filePath.split("/");
                      return segments[segments.length - 1];
                    },
                    processContent: function(content) {
                        content = content.replace(/^[\x20\t]+/mg, '').replace(/[\x20\t]+$/mg, '');
                        content = content.replace(/^[\r\n]+/, '').replace(/[\r\n]*$/, '\n');
                        return content;
                    }
                }
            }
        }

And running the following:

$ grunt handlebars

I'm using the following (Mac):

grunt-contrib-handlebars: v0.5.9
Node: v0.8.8
Grunt: v0.4.1

Return partial template when using AMD

I'd love to see the possibility of returning a partial template when wrapping with AMD.

For example something like this:

partials.push('var partialTemplate = ' + compiled + ';');
   if (options.partialsUseNamespace === true) {
      partials.push('Handlebars.registerPartial('+JSON.stringify(filename)+', '+nsInfo.namespace+'['+JSON.stringify(filename)+'] = partialTemplate);');
} else {
   partials.push('Handlebars.registerPartial('+JSON.stringify(filename)+', partialTemplate);');
}
if(options.amd && options.namespace === false) {
   partials.push('return partialTemplate;');
}

Namespace automatically wrapped in this[...] makes sub-namespace for templates impossible

A configuration such as this:

handlebars: {
    compile: {
        options: {
            namespace: "GUI.Templates"
        },
        files: {
            "build/templates.js": "templates/*"
        }
    }
}

Results in:

this['GUI.Templates']['myTemplate'] = ...

Instead of:

GUI.Templates['myTemplate'] = ...

If the user wants to define their templates within this, they can provide the following configuration:

handlebars: {
    compile: {
        options: {
            namespace: "this.GUI.Templates"
        },
        files: {
            "build/templates.js": "templates/*"
        }
    }
}

It does not make sense to wrap with this[...] by default and it prevents a common use case.

Using handlebars with require js

I'm migrating an application from brunch to grunt and i'm having some troubles understanding how to compile our handlebars templates to be used with require.js.

When compiling the templates with amd: true, the result looks like this:

define(['handlebars'], function(Handlebars) {

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

this["JST"]["src/templates/myTemplate.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers; data = data || {};

  return "<div>some comtent</div>\n";});

return this["JST"];
});

The only way to make this compiled template work in our app, is by doing something like this in the backbone.js view:

   @template: ->
        t = require 'templates/myTemplate.hbs'
        return t['src/templates/index.hbs']

   getTemplateFunction: @template

As opposed to this code in the previous app:

   @template: require 'templates/myTemplate.hbs'

I'm not sure if this is the right approach, but is it possible to get a compiled template that looks like this with this task?

define(['handlebars'], function(Handlebars) {


module.exports = Handlebars.template(function(Handlebars,depth0,helpers,partials,data) {
    helpers = helpers || Handlebars.helpers; data = data || {};
    return "<div>some comtent</div>\n";
});

return module.exports;
});

Compiled output different than terminal output

I'm working on a project and I'm noticing a weird problem - may be my misunderstanding about how this module is supposed to work

When I run this grunt task I'm getting the following output

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, when I run the handlebars npm module from terminal I get a slightly different output:

(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;
  });
})();

As you can see the only difference is that the terminal output is wrapped in an anon function

(function() {
  var template = Handlebars ...
})();

However, it is making the difference between the template working and not working.

I'm using the following coffeescript:

data = error:thrownError
errorTemplate = Handlebars.templates['err.hbs']
temp = errorTemplate(data)

That code works with the terminal compiled template - but not with the grunt module compiled template.

Not sure why but thought I would post in case it is relevant.

Rich

TypeError: Cannot read property '_' of undefined

โžœ  grunt -v                 
path.existsSync is now called `fs.existsSync`.
Initializing
Command-line options: --verbose

Reading "grunt.js" config file...OK

Registering "grunt-contrib-handlebars" local Npm module tasks.
Loading "handlebars.js" tasks and helpers...ERROR
>> TypeError: Cannot read property '_' of undefined
>>     at Object.module.exports (/home/test/projects/test/node_modules/grunt-contrib-handlebars/tasks/handlebars.js:12:21)
>>     at loadTask (/usr/lib/node_modules/grunt/lib/grunt/task.js:156:10)
>>     at /usr/lib/node_modules/grunt/lib/grunt/task.js:192:7
Initializing config...OK
Loading "grunt.js" tasks and helpers...OK
Tasks: test

No tasks specified, running default tasks.
Running tasks: default
<WARN> Task "default" not found. Use --force to continue. </WARN>

Aborted due to warnings.
โžœ  npm list grunt -g     
/usr/local/lib
โ””โ”€โ”€ [email protected] 

โžœ   npm -v                   
1.1.69
โžœ   node -v                  
v0.8.16

'node: true' option.

Hi, I'm using v0.3.3 & I was just wondering if you could provide some more info on how to use the 'node: true' option.

I have my template.hbs, the compiled template.js and my backbone view (view.js) all in the same directory.

handlebars: {
      compile: {
        options: {
          namespace: 'MyApp.Templates',
          node: true
        },
        files: {
          "public/js/views/card/list/template.js": "public/js/views/card/list/template.hbs"
        }
    }
}

In my backbone view I'm requiring the handlebars template like so:

class List extends Backbone.View
    template: require('./template')

rendering this, outputs this error in the inspector :

Uncaught [object Object]

> template = Handlebars.compile($(this.template).html());

Any help explaining how to utiise this would be appreciated.

How to include custom Handlebars helpers

I'm working in a project, generated with Yeoman generator-backbone.
RequireJS and Handlebars templates. The templates are precompiled with grunt-contrib-handlebars.
This is the handlebars task in Gruntfile.js:

handlebars: {
            compile: {
                options: {
                    namespace: 'HBS',
                    amd: true,
                    processName: function (filename) {
                        return filename
                            .replace(/app\/src\/modules\//, '')
                            .replace(/\.hbs$/, '');
                    }
                },
                files: {
                    '.tmp/scripts/hbs.js': [
                        '<%= yeoman.app %>/src/modules/*/templates/*.hbs'
                    ]
                }
            }
        }

I defined a few custom Handlebars helpers.
My main require config looks like this:

require.config({
  paths: {
       ...
        'handlebars': '../vendor/bower/handlebars/handlebars',
        'hbs': '/scripts/hbs',
        'handlebarshelpers': 'core/templates/helpers',
  },

deps: [
        ...
        'handlebarshelpers',
        'main'
    ]
},

This works perfectly in dev (using 'grunt server').
But after building, the dist application prints following error to the console:

Uncaught Error: Missing helper: 'compare' 

Is there any best practice how to include custom helpers with precompiled templates?
Any idea what could be wrong?

compiling partials as templates

Outside of node.js I have always set all my templates to be partials so I can use any template anywhere. I cannot figure out a way to do this with grunt pre-compilation. Is there a way to do this?

minimatch support

Ideal Config:

handlebars: {
      compile: {
          options: {
              namespace: "App.templates",
              processName: function (file_name) {
                  var name = file_name.split('/');
                  return name[name.length - 1].split('.')[0];
              },
              compilerOptions: {
                  knownHelpers: {
                      //"my-helper": true
                  },
                  knownHelpersOnly: true,
              }
          },
          files: [
              {
                  src: [
                      'src/templates/compress/*.html',
                      '!src/templates/compress/_scripts.html',
                      '!src/templates/compress/_config_logged_out.html',
                      '!src/templates/compress/__base_logged_out.html',
                      '!src/templates/compress/home_logged_out.html',
                      '!src/templates/compress/links_logged_out.html',
                      '!src/templates/compress/links_logged_out.html'
                  ],
                  dest: 'src/js/template/built/templates.js',
                  expand: true,
                  flatten: true,
                  filter: 'isFile'
              }
          ]
      }
  }

Cannot call method template of undefined

getting method undefined error on load.

thing.hbs:

<div class="notfoundevents"><p>No events for you</p></div>

thing.js:

define(['handlebars'], function (Handlebars) {

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

    this["SST"]["source/templates/thing.hbs"] = Handlebars.template(function (Handlebars, depth0, helpers, partials, data) {
        this.compilerInfo = [2, '>= 1.0.0-rc.3'];
        helpers = helpers || Handlebars.helpers;
        data = data || {};


        return "<div class=\"notfoundevents\"><p>No events for you</p></div>";
    });

    return this["SST"];

});

gruntfile:

   handlebars: {
            compile: {
                options: {
                    namespace: 'SST',
                    processPartialName: function (filePath) {
                        var pieces = filePath.split("/");
                        return pieces[pieces.length - 1];
                    },
                    amd: true
                },
                files: {
                    "source/javascripts/templates/thing.js": "source/templates/thing.hbs"
                }
            }
        }

All and any help greatly appreciated :)

Using grunt-contrib-handlebars with ember.js

I've noticed many people are getting stuck trying to use this project when compiling handlebars templates for their ember.js application. I've been suggesting people use (grunt-ember-templates)[https://github.com/dgeb/grunt-ember-templates] or (grunt-ember-handlebars)[https://github.com/yaymukund/grunt-ember-handlebars] but wanted to be sure I'm not missing something. For example these questions on stack overflow:

  • (how-does-ember-js-reference-grunt-js-precompiled-handlebars-templates)[http://stackoverflow.com/questions/15607008/how-does-ember-js-reference-grunt-js-precompiled-handlebars-templates]
  • (using-grunt-handlebars-together-with-ember-to-split-templates-in-separate-files)[http://stackoverflow.com/questions/15877005/using-grunt-handlebars-together-with-ember-to-split-templates-in-separate-files]

Is there an easy way to use grunt-contrib-handlebars with ember or would you recommend one of these other projects?

Either way, might be a good idea to add something about this to the README.

Uncaught TypeError: Object #<Object> has no method 'merge'

For some reason this merge method doesn't exist
helpers = this.merge(helpers, Handlebars.helpers);

When I do a console.log(this) in the compiled javascript I get an object but can't find the merge within it's own property or in the prototypical chain.
I'm sure this is a versioning problem with handlebars.js and handlebars.runtime.js
I was using v0.5.4 with handlebars 1.0.0-rc.4

Example for outputting as typical Handlebars precompiling explanation

Hey, I'm a little confused at the way these are compiled in comparison to how I was doing it before (how Handlebars.js actually tell you to do it).

http://handlebarsjs.com/precompilation.html
"The compiler will insert templates in Handlebars.templates. If your input file is person.handlebars, the compiler will insert it at Handlebars.templates.person."

Is it possible to replicate this at all by config?

Was hoping to do

'public/js/templates.js': 'public/js/templates/*.handlebars'

And then use them by their filename so:

game.handlebars = Handlebars.templates.game
thing.handlebars = Handlebars.templates.thing

AMD definition path

Is there a way to configure the AMD definition path to handlebars?

At the moment it's outputting:

define(['handlebars'], function(Handlebars) { ...

and with my current setup it needs to be:

define(['../../libs/handlebars'], function(Handlebars) { ...

Any help would be appreciated!

AMD option not working for me.

I have been monitoring this project and I updated to the latest with all the pull requests integrated. I am using "grunt": "0.4.0rc7", "grunt-contrib-handlebars": "~0.5.1rc7". The new processContent method works for me as well as ignoring the namespace if set to false, but the AMD isn't. Am I the only one with this issue?

Partial pre-compiled output incorrect

handlebars: {
          compile: {
            options: {
              amd: "true",
              namespace: false
            },

running handlebars task on file _mypartial.hbs

actual output in _mypartial.js has extra return

Handlebars.registerPartial("mypartial", return Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {

expected output should not have an extra return

Handlebars.registerPartial("mypartial", Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {

successful precompilation of partial is also shown here in @pdokas comment
#49

Handlebars.registerPartial("PARTIAL_NAME", Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {

Request: Compile-only option.

For validation purposes, it would be great to have an option to compile without writing to file. At present we're using this in a build tool in a series of tasks which validate several files before publish.

Our handlebars templates aren't converted to JST for publishing, but we'd like to know they're good to go before hand. We'd like to stick with the grunt-contrib-* tasks, and would love to see this feature added.

Get RC on npm

The other grunt-contrib-* modules has their grunt 0.4.* compatible versions updated on npm, is there a reason grunt-contrib-handlebars do not?

wrapped option not working?

Not sure if I am missunderstanding the wrapped option, but setting it to true results in no change.

Using:
grunt-cli v0.1.6
grunt v0.4.0
grunt-contrib-handlebars v0.5.6

handlebars portion of my grunt file:

handlebars: {
      compile: {
        options: {
          namespace: 'Reddit',
          wrapped: true
        },
        files: {
          'libs/templates.js': 'templates/*.handlebars'
        }
      }
    },

Here is what setting wrapped to true and false outputs:

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

this["Reddit"]["templates/post.handlebars"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Handlebars.helpers; data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


  buffer += "<li>\n  <div class=\"row\">\n    <a href=\"";
  if (stack1 = helpers.url) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.url; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\" class=\"post-link\">";
  if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "</a>\n  </div>\n  <div class=\"row\">\n    ";
  if (stack1 = helpers.subreddit) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.subreddit; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\n  </div>\n</li>";
  return buffer;
  });

this["Reddit"]["templates/postimage.handlebars"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Handlebars.helpers; data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


  buffer += "<li>\n  <div class=\"row\">\n    <a href=\"";
  if (stack1 = helpers.url) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.url; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\" class=\"post-link\">";
  if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "</a>\n  </div>\n  <div class=\"row\">\n    ";
  if (stack1 = helpers.subreddit) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.subreddit; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\n  </div>\n  <div class=\"row\">\n    <img src=\"";
  if (stack1 = helpers.url) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.url; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\" />\n  </div>\n</li>";
  return buffer;
  });

this["Reddit"]["templates/posttext.handlebars"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Handlebars.helpers; data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


  buffer += "<li>\n  <div class=\"row\">\n    <a href=\"";
  if (stack1 = helpers.url) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.url; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\" class=\"post-link\">";
  if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "</a>\n  </div>\n  <div class=\"row\">\n    ";
  if (stack1 = helpers.subreddit) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.subreddit; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\n  </div>\n  <div class=\"row\">\n    ";
  if (stack1 = helpers.selftext) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.selftext; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\n  </div>\n</li>";
  return buffer;
  });

this["Reddit"]["templates/postyoutube.handlebars"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Handlebars.helpers; data = data || {};
  var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;


  buffer += "<li>\n  <div class=\"row\">\n    <a href=\"";
  if (stack1 = helpers.url) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.url; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\" class=\"post-link\">";
  if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "</a>\n  </div>\n  <div class=\"row\">\n    ";
  if (stack1 = helpers.subreddit) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.subreddit; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\n  </div>\n  <div class=\"row\">\n    <iframe id=\"ytplayer\" type=\"text/html\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/";
  if (stack1 = helpers.youtubeId) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
  else { stack1 = depth0.youtubeId; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
  buffer += escapeExpression(stack1)
    + "\"\n  frameborder=\"0\"/>\n  </div>\n</li>";
  return buffer;
  });

Question: One file per each folder

Hello, thanks for providing the module for all of us. I need some help defining the files object:
files: {
"apps/APP_NAME/js/package/hbs/compiled.js": "apps/APP_NAME/js/package/hbs/.hbs"
}
I have multiple APP_NAME folders and would be really happy if I could make a /js/package/hbs/compiled.js for each of them with only the APP_NAME/js/package/hbs/
.hbs templates compiled into it.

Can you advise how to do this? As far as I know, the ** will not work.

Cheers,

Mike

Node 0.10 on Windows fail to build

After upgrading to node 0.10, the now build fails

npm http GET http://registry.npmjs.org/grunt-contrib-handlebars/-/grunt-contrib-handlebars-0.5.8.tgz
npm ERR! [email protected] install: `node ./build.js`
npm ERR! `cmd "/c" "node ./build.js"` failed with 8
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the fibers package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./build.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls fibers
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node -v v0.10.0
npm ERR! npm -v 1.2.14
npm ERR! code ELIFECYCLE

compiled version

looks like newer v1.0.rc.2 versios of handlebar runtime requires compiled version to be set within the wrapped function:

this.compiledVersion = '1.0.rc.2';

Windows gives error with package.json file

http://stackoverflow.com/questions/19743779/windows-gives-error-with-package-json-file?noredirect=1#comment29338339_19743779

I wanted my Package.json to be something like this

{
  "name": "Billing",
  "version": "0.0.0",
  "dependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-contrib-compass": "~0.5.0",
    "grunt-contrib-uglify": "~0.2.2",
    "grunt-contrib-cssmin": "~0.6.2",
    "matchdep": "~0.1.2"
  },
  "devDependencies": {
    "grunt-contrib-handlebars": "~0.5.4",
    "grunt-contrib-less": "~0.8.1"
  }
}

I tried this using npm install but got this error

package.json must be actual JSON, not just JavaScript.

So I used command line to create json, and added dependencies. What I found was that most of the packages were installed without giving this errors, and also my package.json got updated correctly by using npm install grunt-contrib-watch --save-dev and so on.

On Windows I am seeing this error only for two packages: for grunt-contrib-uglify" as well as grunt-contrib-handlebars. So my JSON file is ending with

{
  "name": "Billing",
  "version": "0.0.0",
  "dependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "grunt-contrib-compass": "~0.5.0",
    "grunt-contrib-cssmin": "~0.6.2",
    "matchdep": "~0.1.2"
  },
  "devDependencies": {
    "grunt-contrib-less": "~0.8.1"
  }
}

wrapcompile default

Added a comment in the commit that changed the wrapcompile functionality. Not sure how to link to it, but the option in the grunt file probably should be "wrapped" instead of "wrap" since that's the one handlebars.js is using.

Error: Cannot read property 'helpers' of undefined in generated file

I'm sure this is just something silly that I'm missing, but I can't seem to figure out what I'm missing here.

So, first of all, I'm attempting to use grunt-contrib-handlebars by itself (without using the full grunt-contrib library)...I have no idea if this is possible or not...but it seemed to work (my grunt script doesn't fail).

So I ran npm install grunt-contrib-handlebars at the command line and everything worked fine.

Then I modified my grunt.js script and added the following:

handlebars : {
    compile : {
        options : {
            namespace : 'Docr.Templates',
            processName : function (filename) {
                return filename.replace(/^.*[\\\/]/, '').replace('.hb', '');
            }
        },
        files : {
            'templates.js' : ['templates/*.hb']
        }
    }
}

And then at the end of the file, just before registering the default task, I added:

grunt.loadNpmTasks('grunt-contrib-handlebars');

When I run my grunt script, it runs fine, and generates the expected templates.js file. But then when I run my app, I get the following error in my browser console:

Uncaught TypeError: Cannot read property 'helpers' of undefined

For the purposes of testing this to get it working, I'm only generating a single template, so the resulting templates.js file is very simple:

this["Docr"] = this["Docr"] || {};
this["Docr"]["Templates"] = this["Docr"]["Templates"] || {};

this["Docr"]["Templates"]["NoMoreDocumentsToProcessDialog"] = function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;



  return "<div class=\"modal-header\">\r\n  <h2 id=\"dialog-title\">You're Done!</h2>\r\n</div>\r\n<div class=\"modal-body\">\r\n   You've reached the end of the stack. There are no more \"Unknown\" documents in the system to process.\r\n</div>\r\n<div class=\"modal-footer\">\r\n    <div class=\"modal-info\"></div>\r\n    <a href=\"#\" id=\"cancel-button\" class=\"btn\">Cancel</a>\r\n <a href=\"#\" id=\"save-button\" class=\"btn btn-primary\">Save</a>\r\n</div>\r\n";};

I am referencing handlebars.js (version 1.0.beta.6) before the reference to templates.js in the host page.

Any idea what I'm missing or what I'm doing wrong?

multiple targets

I'm fairly new to grunt, but the specifying multiple targets (example below) doesn't seem to work. Or am I missing something?

handlebars: {
  dist: {
    compile: {
      files: {
       'src/js/app/hbs/detailsTemplates.js' : ["src/templates/details/**/*.hbs"],
       'src/js/app/hbs/themeTemplates.js' : ["src/templates/timeline/**/*.hbs"]
      }
    }
  },
  dev: {
    compile: {
      files: {
       'src/js/app/hbs/detailsTemplates.js' : ["src/templates/details/**/*.hbs"],
       'src/js/app/hbs/themeTemplates.js' : ["src/templates/timeline/**/*.hbs"]
      }
    }
  }
},

passing json data to template

Is there a way to add an options for passing json data to a template? Eg:

nav.json:

{
  "links": [
    {
      "href": "page1.html",
      "text": "Page 1"
    },
    {
      "href": "page2.html",
      "text": "Page 2"
    }
  ]
}

template.hbs

<ul>
  {{#each nav.links}}
    <li><a href="{{this.href}}">{{this.text}}</a></li>
  {{/each}}
</ul>

Dynamic file mapping not working properly

I'm trying to compile as in Grunt Docs, using dynamic file mapping, but the result is somewhat strange.

        # Gruntfile.coffee
        handlebars:
            compile:
                options:
                    namespace: "App.templates"

                files:[
                    expand: true
                    cwd: 'src/'
                    src: ['**/*.hbs']
                    dest: 'dest/templates.js'
                ]

A few variations were used there, but my conclusion was that grunt-contrib-handlebars is not handling this syntax of file mapping properly or I'm very confused about how it works.

Any lights?

partials problem

hey,

I created a namespace "tpl"

made a partial

<p>
    <span>{{format_email username}}</span> op <span>{{format_date datum}}</span><br/><br/>
    {{&feedback}}
</p>

precompiled it via the plugin

now I have this

Handlebars.registerPartial("feedback_part", Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [2,'>= 1.0.0-rc.3'];
helpers = helpers || Handlebars.helpers; data = data || {};
  var buffer = "", stack1, stack2, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function";


  buffer += "<p>\n    <span>";
  options = {hash:{},data:data};
  buffer += escapeExpression(((stack1 = helpers.format_email),stack1 ? stack1.call(depth0, depth0.username, options) : helperMissing.call(depth0, "format_email", depth0.username, options)))
    + "</span> op <span>";
  options = {hash:{},data:data};
  buffer += escapeExpression(((stack1 = helpers.format_date),stack1 ? stack1.call(depth0, depth0.datum, options) : helperMissing.call(depth0, "format_date", depth0.datum, options)))
    + "</span><br/><br/>\n    ";
  if (stack2 = helpers.feedback) { stack2 = stack2.call(depth0, {hash:{},data:data}); }
  else { stack2 = depth0.feedback; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; }
  if(stack2 || stack2 === 0) { buffer += stack2; }
  buffer += "\n</p>";
  return buffer;
  }));

if I try to use the partial Handlebars is unable to find it.
If I console.log Handlebars.partials I get Object {feedback_part: undefined}

any ideas what's wrong?

thanks.

Automatically including runtime

I'd like to add the ability to automatically prepend the Handlebars runtime to the compiled js file.

Right now, I'm doing this:

...
concat: {
    experiment: {
        files: {
            'assets/compiled/templates.js': ['node_modules/grunt-contrib-handlebars/node_modules/handlebars/dist/handlebars.runtime.js','assets/compiled/templates.js']
        }
    }
},

How about an option called runtime that accepts a boolean and is false by default?

CommonJS auto-require Handlebars

Is there a reason for not having an auto-require option for Handlebars when using the CommonJS compiled version?

For example:

options: {
  namespace: false,
  commonjs: true,
  require: 'handlebars'
}

This would add a var Handlebars = require('handlebars'); to the compiled template module, so the user doesn't have to require and passthrough the Handlebars library in every module that needs templates.

Current usage:

var Handlebars = require('handlebars');
var Templates = require('./templates')(Handlebars);

Proposed change would allow:

var Templates = require('./templates');

Am I missing something, or would this have a decent use case? I'd be happy to contribute, just wanted to make sure I'm not missing something that already exists.

Addition of task event emitting?

I'm currently working with the following task definition for grunt-contrib-handlebars to compile my server-side handlebars templates down into templates accessible on the client:

var templateMap = [];

handlebars: {
  compile: {
    options: {
      amd: true,
      namespace: false,
      processName: function(filePath) {
        templateMap.push(filePath.replace('.hbs', ''));
        return filePath;
      }
    },
    files: [{
      expand: true,
      cwd: 'src/app/views/',
      src: ['**/*.hbs'],
      dest: 'public/scripts/templates/',
      ext: '.js'
    }]
  }
}

// do something with templateMap after task finishes

I've run into a problem where I need to grab each of the template names and stash them in an array for later use in my Gruntfile.

This seems like an odd way to do this and I'm wondering if it would benefit others, as well as myself, to emit some events at key places during task execution.

I think I'm going to fork for now and just implement it myself so it doesn't feel too hacky, but I figured I'd put it out there and see if the community had need of this type of addition.

Update for compatibility with grunt 0.4.0rc5

I need someone to help update this plugin to work with grunt 0.4.0rc5.

I had to revert the whole file src-dest mappings implicit iteration abstraction per gruntjs/grunt#606, and once again, multi tasks have to iterate over this.files manually. In addition, there's a new this.filesSrc array that contains a reduced, uniqued set of all matched src files in case the task is read-only and only cares about source files.

See:

Notes:

  • A user may specify a new option nonull in addition to src to tell grunt to keep patterns or filepaths that don't actually match files. Because of this, the task shouldn't explode if a nonexistent src filepath is encountered. I handle this in the grunt-contrib-concat by warning if not grunt.file.exists but not failing the task.

Guidelines for updating / publishing this plugin:

  • Change this project's version number to one ending in "rc5" so that it's clearer that it works with grunt 0.4.0rc5. If the existing version number doesn't end in an "a" or "rc" increment the patch version. Eg, jshint went from 0.1.0 -> 0.1.1rc5
  • Ensure grunt 0.4.0rc5-compatible plugins are specified in package.json devDependencies like this (grunt-contrib-internal can be "*")
  • Update the CHANGELOG like this
  • Regenerate the README.md file via grunt.
  • Delete node_modules, run npm cache clean and re-run npm install to test.
  • Publish to npm using --tag=master (not latest)

Rendering HTML directly

I'd like to add support for grunt-contrib-handlebars to allow it to render handlebars templates directly to HTML.

Thoughts on option names ?

handlebars: {
  options: {
    target: 'html',  // Defaults to 'js' ?
    data: {
      // Context goes here
      foo: 3251
    }
  }
}

Something like the above.. unless you have a better idea for the target name.

Filenames with single quotes break resulting template file

If your filename, for some awful reason, contains a single quote, the resulting template file will not work as it wraps template names with single quotes. Single quotes should be removed from the resulting templates name or escaped.

Handlebars Namespace config

I really appreciate the namespace config option, so that I can put my templates in (e.g.) MyApp.Templates. However, I've also got my Handlebars namespaced as MyApp.Handlebars. Is there a way to make the generated JS templates obey that namespace? As of now, they look something like this (for a simple <h1>Hello, World.</h1> template):

this["MyApp"] = this["MyApp"] || {};
this["MyApp"]["Templates"] = this["MyApp"]["Templates"] || {};

this["MyApp"]["Templates"]["consumer/sweeps/test.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};



  return "<h1>Hello, World.</h1>\n\n";
  });

Note the explicit call to Handlebars. Can I change that to (e.g.) MyApp.Handlebars so it looks something like this?

this["MyApp"] = this["MyApp"] || {};
this["MyApp"]["Templates"] = this["MyApp"]["Templates"] || {};

this["MyApp"]["Templates"]["consumer/sweeps/test.hbs"] = MyApp.Handlebars.template(function (MyApp.Handlebars,depth0,helpers,partials,data) {
  this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, MyApp.Handlebars.helpers); data = data || {};



  return "<h1>Hello, World.</h1>\n\n";
  });

Troubles with compiled template result

I've changed grunt-handlebars for grunt-contrib-handlebars and now I've gots errors on my templates.js like:

TypeError: depth0 is undefined

stack1 = depth0.myVar;

I understood that I had to change my template backbone attribute from template: Handlebars.template['channel-details'] to template: this['jst']['channel-details']. Now, my template is known by the app. But I've got these depth0 unknown errors.

Any idea?

Using with yeoman and grunt 0.4.1 have the error no method 'expandFiles'

Running "handlebars" task

Running "handlebars:compile" (handlebars) task
Verifying property handlebars.compile exists in config...OK
Files: [no src] -> app/temp/compiled-templates.js
Options: namespace="MyApp.Templates", wrapped, processName=undefined
Warning: Object # has no method 'expandFiles' Used --force, continuing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.