/requirejs-hogan-plugin

RequireJS Hogan / Mustache Plugin

Primary LanguageJavaScript

RequireJS mustache / hogan.js plugin

Load mustache / hogan.js templates dynamically during development and compile them during build to achieve greater performance.

Basic Usage

Define an external template like foo.mustache:

<div class="foo">
    <h1>{{title}}</h1>
    <ul>
        {{#names}}
        <li>{{.}}</li>
        {{/names}}
    </ul>
</div>

Load it with the hgn plugin:

// this will load the "foo.mustache" file
require(['hgn!foo'], function(foo){
    // the plugin will return the `render()` method of the `Hogan.Template`
    var markup = foo({
        title : 'Hello!',
        names : ['world', 'foo bar', 'lorem ipsum', 'nurse']
    });
    console.log(markup);
});

During development the template file will be loaded using the RequireJS text plugin and template will be compiled automatically. During optimization it will pre-compile the template and store it as pure JavaScript for better performance:

define("hgn!foo", ["hogan"], function(hogan){  var tmpl = new hogan.Template(function(c,p,i){var _=this;_.b(i=i||"");_.b("<div class=\"foo\">\r");_.b("\n" + i);_.b("    <h1>");_.b(_.v(_.f("title",c,p,0)));_.b("</h1>\r");_.b("\n" + i);_.b("    <ul>\r");_.b("\n" + i);if(_.s(_.f("names",c,p,1),c,p,0,71,105,"{{ }}")){_.rs(c,p,function(c,p,_){_.b("        <li>");_.b(_.v(_.d(".",c,p,0)));_.b("</li>\r");_.b("\n");});c.pop();}_.b("    </ul>\r");_.b("\n" + i);_.b("</div>\r");_.b("\n");return _.fl();;}, "", hogan);  return function(){ return tmpl.render.apply(tmpl, arguments); };});;

The plugin code is only required for dynamic load so you can use the r.js setting stubModules to remove the text! and hgn! plugins during build, see test/build.js for example.

Example

Example files are inside the test folder, to test build run:

cd test
node build

It will update the test/scripts/main_built.js file.

License

Released under the MIT license.

Other plugins

You should also check the awesome RequireJS Handlebars Plugin created by Alex Sexton and the list of plugins on RequireJS wiki.