Monday, February 24, 2014

Handlebars integration with Yeoman’s webapp-generator

I was looking for an instruction on how to add Handlebars to my application based on Yeoman’s webapp-generator. There is an instruction on the old wiki on GitHub, but it’s out-of-date. For this exercise I’ve been using Yeoman 1.1.2 and the 0.47 version of the webapp-generator.

First off, go ahead with step 1 and 2 (but obviously using the latest versions).

There’s no need to load the "grunt-contrib-handlebars" in your Gruntfile.js (step 3), as "require('load-grunt-tasks')(grunt);" is used to load all referenced tasks.

I did some changes to the file structure in step 4, but I guess that’s a matter of taste? One thing to note is the change from “temp” to “.tmp” as this is the temporary directory name being used in other places:

handlebars: {
  compile: {
    files: {
      '.tmp/scripts/compiled-templates.js': [
        '<%= yeoman.app %>/templates/**/*.hbs'
      ]
    },
    options: {
      namespace: 'MyApp.Templates',
      wrapped: true,
      processName: function(filename) {
        // funky name processing here
        return filename
                .replace(/^app/, '')
                .replace(/\.hbs$/, '');
      }
    }
  }
}

The watch task needs some additions to it, as well (step 5). Note the addition on watching .js-files in livereload:

handlebars: {
    files: ['<%= yeoman.app %>/templates/*.hbs'],
    tasks: ['handlebars']
},
livereload: {
    options: {
        livereload: '<%= connect.options.livereload %>'
    },
    files: [
        '<%= yeoman.app %>/{,*/}*.html',
        '.tmp/styles/{,*/}*.css',
        '.tmp/scripts/{,*/}*.js',
        '<%= yeoman.app %>/images/{,*/}*.{gif,jpeg,jpg,png,svg,webp}'
    ]
}

Step 6 handles the configuration of Handlebars tasks being run during build, test and serve:
// Run some tasks in parallel to speed up build process
concurrent: {
    server: [
        'compass:server',
        'copy:styles',
        'handlebars'
    ],
    test: [
        'copy:styles',
        'handlebars'
    ],
    dist: [
        'compass',
        'copy:styles',
        'handlebars',
        'imagemin',
        'svgmin'
    ]
}

Don't forget to get the actual Handlebars package using "bower install handlebars" (step 7).

In step 8, as I changed the file structure - just add
<script src="scripts/compiled-templates.js"></script>
and you're done!

/Mattias

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks, this was very helpful.

    FYI: the old wiki link is now here:

    https://github.com/yeoman/yeoman.io/blob/master/app/wiki-archives/Handlebars-integration.md

    ReplyDelete
  3. nice this blog.
    You put really very helpful information. Keep it up. Keep blogging. I’m looking to reading your next post.

    โกเด้นสล็อต
    gclub
    gclub

    ReplyDelete