twitter / hogan.js

A compiler for the Mustache templating language
http://twitter.github.io/hogan.js
Apache License 2.0
5.14k stars 431 forks source link

add es6 option to hulk --wrapper #214

Closed paulcpederson closed 8 years ago

paulcpederson commented 9 years ago

Add Wrapper Option to Hulk for ES6 Modules

Was working on a project recently that used ES6 modules and hogan.js. I needed a way to load compiled templates (compiled with hulk) with the ES6 module loader. Essentially this adds --wrapper es6. If you compile with this option, hulk generates a file that imports hogan.js as a dependency, then exports each template as part of the module. Say you had a folder named templates with two templates inside user.mustache and product.mustache. Now when you run hulk templates/*.mustache -w es6 > templates.js the following will be output to templates.js:

import Hogan from 'hogan.js'; 
export var users = new Hogan.Template({...etc});
export var products = new Hogan.Template({...etc});

Now, in your other modules, you can load these templates like this:

import * as templates from './templates.js';

That would make each compiled template available off thte templates variable, so you could render the above users template like this:

templates.users.render(/* data */);

This has proved to be pretty rad for the project, so I thought I'd open a pr from my fork and see if you guys were interested.

Also, my editor automatically strips trailing whitespace, sorry that partially obscures the meat of this pull request... :grimacing: