Load mustache / hogan.js templates dynamically during development and compile them during build to achieve greater performance.
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.
This plugin also supports partials however it needs a slightly different argument to the standard hogan.js method. Eg:
require(['hgn!foo', 'hgn!bar'], function(foo, bar){
// the plugin will return the `render()` method of the `Hogan.Template`
var markup = foo({
title : 'Hello!',
names : ['world', 'foo bar', 'lorem ipsum', 'nurse']
},
{
// note the .template, it is required because the plugin returns the `render()` method directly
bar: bar.template
});
console.log(markup);
});
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.
- update text plugin to 2.0.10 fixing bug related to node-webkit.
- update Hogan to v3.0
- add
template
property to the compiled template. - fix in case
config.hgn
isn't defined.
- add
compilationOptions
support. - add pragmas to remove compiler during build.
- return
Template#render
method instead of theHogan.template
object.
- initial release.
Released under the MIT license.
You should also check the awesome RequireJS Handlebars Plugin created by Alex Sexton and the list of plugins on RequireJS wiki.