README.md

grunt-templatize

Super simple grunt task to convert one or more handlebars-like template files into a Javascript module. Supports AMD, commonjs, and namespaced module formats.

Templates support iteration using {{#each items}}{{/each}} markup. For this to work, generated templates assume you have _.map available, either via lodash, underscore, or other means. Configuration options are available to use your own map-like function.

Simple Usage Example

First, make sure you have node.js and npm properly installed and working. You will also need to have grunt-cli installed globally:

npm install grunt-cli -g

Create a new project folder with package.json file and install dependencies from npm:

HTML Fragments

By default, grunt-templatize will minify all of your HTML templates.

If you have templates that contain ill-formed HTML, as is often the case, then using the HTML Minifier feature will break your templates. This is because the minifier also makes the HTML well-formed by adding missing closing tags and removing extraneous closing tags.

To turn off the HTML minifier, set htmlminEnable: false. Note that the option can be set differently for each target, as in this example:

In many cases, HTML fragment templates are very short and can live on a single line. By setting htmlminMultiLines: true, any single-line templates will not be minified, but any templates that contain more than one line will be minified.

Iteration in Templates

Iteration is supported using {{#each item}} and {{/each}} tags in your templates. When these tags are used, the templatized output includes calls to the _.map() function. If you are using Underscore or Lodash, this is available out of the box. If not, any implementation that is API compatible with the Underscore version should work.

Note that you may need to provide a custom prefix and suffix to use iteration effectively. For instance, to use Underscore instead of Lodash in an AMD module, you could use this configuration:

Note that templatize supports nested {{#each}}'s, and within an inner scope, you can reference properties in the outer scope. This is done by using ../foo notation. You can step up multiple scope levels by repeating the dots, i.e. ../../../foo.

Partials in Templates

Templatize also supports template partials using the {{>partial}} directive. Any template can be used as a partial and can be embedded within the output of another template. The model passed into a partial is the current context at the time the partial is called.

Here is an example of using a partial:

list.tmplz:

<h1>{{title}}</h1>
<ul>
{{#each items}}
{{>listitem}}
{{/each}}
</ul>

listitem.tmplz:

<li>
<span>{{name}}</span>
</li>

Note that you cannot reference properties in the calling function from within a partial. You can only access properties on the model that was passed to the partial.