thierryc / grunt-handlebars-layouts

A grunt.js task to render Handlebars templates against a context & produce HTML
MIT License
14 stars 10 forks source link

Grunt Handlebars Layouts

Maintainers Wanted

Handlebars helpers which implement Jade-like layout blocks.

A grunt.js task to render Handlebars templates against a context & produce HTML.

If you want to pre-compilation your Handlebars use the grunt-contrib-handlebars Grunt task. This task will pre-compile multiple templates into a single file.

Resources

About

This task renders Handlebars templates against a context to produce HTML.

Inspired by grunt-dust-html and handlebars-layouts

Getting Started

This plugin requires Grunt ~0.4.0

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-handlebars-layouts --save-dev

Next, add this line to your project's grunt file:

grunt.loadNpmTasks("grunt-handlebars-layouts");

This plugin was designed to work with Grunt 0.4.x. If you're still using grunt v0.3.x it's strongly recommended that you upgrade, but in case you can't please use v0.3.3.

Lastly, add the configuration settings (see below) to your grunt file.

Documentation

This task has two required properties, src and dest. src is the path to your source file and dest is the file this task will write to (relative to the grunt.js file). If this file already exists it will be overwritten.

  files: {
    'dest.html': 'src.html'
  },

An example configuration looks like this:

  grunt.initConfig({
    handlebarslayouts: {
      home: {
        files: {
          'dist/home.html': 'src/home.html'
        },
        options: {
          partials: [
            'src/partials/*.hbs',
            'src/layout.html'
          ],
          modules: [
            'src/helpers/helpers-*.js'
          ],
          basePath: 'src/',
          context: {
            title: 'Layout Test',
            items: [
              'apple',
              'orange',
              'banana'
            ]
          }
        }
      }
    }
  });
  grunt.registerTask('default', ['handlebarslayouts']);

Optional Configuration Properties

This plugin can be customized by specifying the following options:

Useful Handlebars Helpers : handlebars-helpers

String: the location to a file containing valid JSON:

context: '/path/to/file.json'

Object: a regular ol' JavaScript object:

context: {
  pageTitle: 'My Awesome Website'
}

Array: an array of contexts, either string (files to parse) or JavaScript objects (>= 0.2.5), or both. Each item in the array will be merged into a single context and rendered against the template:

context: [
  'path/to/context.json',
  'path/to/another/context.json',
  { more: 'data' }
]

Special Var In Context

__filename (add in 0.2.7)

This is the resolved local path of this src file.

use it like {{ __filename }}

or in combination with a helper

{{slug __filename}}

Take a look to the example/example_4/.

Template example

{{#extend "layout"}}
    {{#append "head"}}
      <link rel="stylesheet" href="https://github.com/thierryc/grunt-handlebars-layouts/blob/master/assets/css/home.css" />
    {{/append}}

    {{#replace "body"}}
      <h2>Welcome Home</h2>

      <ul>
        {{#items}}
          <li>{{.}}</li>
        {{/items}}
      </ul>
    {{/replace}}

    {{#prepend "footer"}}
      <script src="https://github.com/thierryc/grunt-handlebars-layouts/raw/master/assets/js/analytics.js"></script>
    {{/prepend}}
{{/extend}}

Layout example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    {{#block "head"}}
          <title>{{title}}</title>
          <meta name="description" content="">
    {{/block}}
  </head>

  <body>
    <div class="site">
      <div class="site-hd" role="banner">
        {{#block "header"}}
            <h1>{{title}}</h1>
        {{/block}}
      </div>

      <div class="site-bd" role="main">
        {{#block "body"}}
            <h2>Hello World</h2>
        {{/block}}
      </div>

      <div class="site-ft" role="contentinfo">
        {{#block "footer"}}
            <small>&copy; 2014</small>
        {{/block}}
      </div>
    </div>

    {{#block "footer"}}
      <p>footer</p>
    {{/block}}

    {{> footer}}
  </body>
</html>

Partial example

<footer>footer</footer>

Custom Helper example

Helpers can either be an object or a single register function. If register is on the object, then it calls the register function, passing in the engine.

module.exports.register = function (Handlebars, options)  { 
  Handlebars.registerHelper('foo', function ()  { 
    return 'foo';
  });
};

MD5 Helper (inspired by handlebars-md5)

'use strict';

var crypto = require('crypto'),
    fs = require('fs');

// The module to be exported
var helpers = {
  md5: function (path) {
    var content = fs.readFileSync(path);
    return crypto.createHash('md5').update(content).digest('hex');
  }
};

// Export helpers
module.exports.register = function (Handlebars, options) {
  options = options || {};

  for (var helper in helpers) {
    if (helpers.hasOwnProperty(helper)) {
      Handlebars.registerHelper(helper, helpers[helper]);
    }
  }
};

Foo and bar Helpers

'use strict';

// The module to be exported
var helpers = {
  foo: function () {
    return 'foo';
  },
  bar: function () {
    return 'bar';
  }
};

// Export helpers
module.exports.register = function (Handlebars, options) {
  options = options || {};

  for (var helper in helpers) {
    if (helpers.hasOwnProperty(helper)) {
      Handlebars.registerHelper(helper, helpers[helper]);
    }
  }
};

Handlebars Markdown Helper

Very simple Markdown for partial. do not forget to add your .md files to the partial list.

options: {
  partials: 'src/partials/*.md',
  ...
}
/**
 * Handlebars Markdown Helpers
 * Copyright (c) 2014 Thierry Charbonnel
 * Licensed under the MIT License (MIT).
 */
'use strict';

var marked = require('marked');

// Export helpers
module.exports.register = function (Handlebars, options) {
  options = options || {};
  options.marked = options.marked || {
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
  };

  Handlebars.registerHelper('md', function(name, context){
    var result;
    marked.setOptions(options.marked);
    // Convert inline markdown by prepending the name string with `:`
    if(name.match(/^:/)) {
      result = marked(name.replace(/^:/, ''));
    } else {
      try {
        result = marked(Handlebars.partials[name]);
      } catch(err) {
        result = '<!-- error -->'; 
      }
    }
    return new Handlebars.SafeString(result); 
  });  
};

npm Helpers

Add it in devDependencies and in gruntfiles.js

"devDependencies": {
  "handlebars-helper-moment": "*"
},

Add it in gruntfiles.js

handlebarslayouts: {
  home: {
    files: {
      'dist/home.html': 'src/home.html',
      'dist/index.html': 'src/index.html'
    },
    options: {
      ...
      modules: ['src/helpers/helpers-*.js', 'handlebars-helper-moment'],
      ...
    }
  }
}

or ( v0.1.4 > )

handlebarslayouts: {
  home: {
    files: {
      'dist/*.html': 'src/*.hsb'
    },
    options: {
      ...
      modules: ['src/helpers/helpers-*.js', 'handlebars-helper-moment'],
      ...
    }
  }
}
npm install

Tested Helpers

suggested structure

A basic Handlebars-layouts site usually looks something like this:

.
├── partials
|   ├── footer.(html|hsb|md)
|   └── header.(html|hsb|md)
├── pages
|   ├── 2014-08-14-Handlebars-layouts-foo.(html|hsb)
|   └── 2014-08-14-Handlebars-layouts-bar.(html|hsb)
├── data
|   └── members.json
├── helpers
|   └── helpers-*.js
└── index.html

grunt file example


/*global module:false*/
module.exports = function(grunt) {
  'use strict';
  grunt.initConfig({

    handlebarslayouts: {
      dev: {
        files: {
          //'dist/home.html': 'src/home.html'
          'dist/*.html': 'src/*.hsb'
        },
        options: {
          partials: ['src/partials/*.hbs', 'src/partials/*.md', 'src/layout.html'],
          basePath: 'src/',
          modules: ['src/helpers/helpers-*.js', 'handlebars-helper-moment'],
          context: {
            title: 'Layout Test',
            projectName: 'Grunt handlebars layout',
            items: [
              'apple',
              'orange',
              'banana'
            ]
          }
        }
      }
    },

    connect: {
      server: {
        options: {
          livereload: true,
          port: 8000,
          base:'dist/',
          open: true
        }
      }
    },

    watch: {
      layout: {
        files: 'src/layout.html',
        tasks: 'handlebarslayouts:dev'
      },
      hsb: {
        files: 'src/**/*.hsb',
        tasks: 'handlebarslayouts:dev'
      },
      options: {
        livereload: true
      }
    },

  });

  grunt.loadTasks('../tasks');

  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['handlebarslayouts']);

  grunt.registerTask('serve', ['handlebarslayouts', 'connect:server', 'watch']);

};

=======

Other interesting projects

Release History and Roadmap

License

Copyright © 2014 Thierry Charbonnel, contributors.
Released under the MIT license

Gulp version.

Soon. Help is welcome. (contact me)