nunjucksify

2.2.0 • Public • Published

Nunjucksify

A transform stream that precompiles nunjucks templates.

  • Compatible with browserify, parcelfiy, and cartero.
  • Uses the node resolve algorithm for nunjucks {% includes %} and {% extends %} tags.
  • Completely encapsulated - does not depend on the global scope.

Include nunjucksify as a package transform. When you require a file that ends with .nunj in that package, nunjucksify will transform that template into a module that returns a nunjucks Template object.

In myWidget.nunj:

<div>{{ menu }}</div>

Now in myWidget.js:

var $ = require( 'jquery' )
var tmpl = require( './myWidget.nunj' );
 
console.log( tmpl.render( { menu : 'chorizo' } ) ); // outputs '<div>chorizo</div>'

But wait, there's more.

Nunjucksify overrides env.getTemplate() within precompiled code so that the node require.resolve() algorthim is used to resolve references in {% includes %} and {% extends %} tags. As a result you can reference templates using relative paths:

{% extends "./morcilla.nunj" %}
 
{% block content %}
Yes, please.
{% endblock %}

Or even reference a template in a module within a node_modules directory:

{% include "my-module/foo.nunj" %}

Poom para arriba!

Usage

Make sure nunjuckify is a dependency of your package.

$ cd path/to/my-package
$ npm install nunjucksify --save

Declare nunjucksify as transform in package.json by adding nunjucksify to the array in the browserify.transform property. Cook 10-15 until crispy.

Caring for the environment

If you want your templates to use a particular nunjucks Environment object, attach the environment object to nunjucks.env. For example, the following makes a subview filter available to all your templates for use with backbone.subviews. (If nunjucks.env is undefined, a new environment is created for each template.)

var nunjucks = require( 'nunjucks' );
 
nunjucks.env = new nunjucks.Environment();
 
nunjucks.env.addFilter( 'subview', function( templateName ) {
    return '<div data-subview="' + templateName + '"></div>';
} );

Using a custom file extension

If you want your templates to use a different extension, you can do so like this (default extension is .nunj):

bundle.transform(nunjucksify, {extension: '.html'}); # For multiple extensions you can use extension: ['.html', '.nunj']

Using slim version of nunjucks

Because all templates are precompiled, nunjucks recommends to use slim version that doesn't include compiler code.

To do this, you should point nunjucks to a different location in your package.json browser config:

"browser": {
  "nunjucks": "nunjucks/browser/nunjucks-slim"
}

License

MIT

Package Sidebar

Install

npm i nunjucksify

Weekly Downloads

77

Version

2.2.0

License

MIT

Last publish

Collaborators

  • pepo
  • go-oleg
  • davidbeck