Package Exports
- template
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (template) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
template

Render templates using any engine. Supports, layouts, pages, partials and custom template types. Use template helpers, middleware, routes, loaders, and lots more. Powers assemble, verb and other node.js apps.
Go to the API documentation
Features
- ~100% test coverage (as of May. 10, 2015) with ~500 unit tests
- Render templates with any engine, including any consolidate, transformers, or any compatible engine. Or, create your own!
- Create custom template types. Built-in types are
page
,layout
andpartial
, but you can create special types for any use case. - Custom loaders. Loaders are simple functions that change how templates are loaded and can be used with template types, or individual templates.
Install with npm
npm i template --save
Table of contents
- Getting started
- Docs
- API
- Register an engine
- Load templates
- Custom templates
- Custom loaders
- API
- Additional docs
- Related
- Running tests
- Build docs
- Contributing
- Authors
- License
(Table of contents generated by verb)
Getting started
var Template = require('template');
var template = new Template();
Define a template
template.page('home.tmpl', 'This home page.');
// add locals
template.page('home.tmpl', 'The <%= title %> page', {title: 'home'});
See other [valid formats].
Render a template
template.render('home.tmpl', function(err, res) {
//=> 'a xyz b'
});
Docs
API
Template
Create a new instance of Template
, optionally passing default options
to initialize with.
Params
options
{Object}: Options to initialize with.
Example
var Template = require('template');
var template = new Template();
.transform
Assign transform fn
to name
or return the value of name
if no other arguments are passed.
Transforms are run immediately during init, and are used to
extend or modify the cache.data
object, but really anything
on the this
object can be tranformed.
Params
name
{String}: The name of the transform to add.fn
{Function}: The actual transform function.returns
{Object}: ReturnsTemplate
for chaining.
Example
template.transform('username', function(app) {
var url = app.cache.data.author.url.split('/');
app.cache.data.username = url[2];
});
.route
Proxy to the engine Router#route
Returns a new Route
instance for the path
.
Routes are isolated middleware stacks for specific paths.
See the Route
api docs for details.
Params
path
{String}
.param
Proxy to Router#param
with one added api feature. The name
parameter can be an array of names.
See the Router#param
docs for more details.
Params
name
{String|Array}fn
{Function}returns
{Object}Template
: for chaining
Delegate .METHOD(...)
calls to router.METHOD(...)
Params
path
{String}- {Function}: Callback
returns
{Object}Template
: for chaining
.all
Special-cased "all" method, applying the given route path
, middleware, and callback.
Params
path
{String}- {Function}: Callback
returns
{Object}Template
: for chaining
Example
template.all(/\.md$/, function (file, next) {
// do stuff next();
});
.view
Get the given view collection
from views. Optionally
pass a name
to get a specific template from the
collection.
Params
collection
{String}name
{String}returns
{Object}
.engine
<%= docs("api-engine") %>
Register the given view engine callback fn
as ext
. If only ext
is passed, the engine registered for ext
is returned. If no ext
is passed, the entire cache is returned.
Params
exts
{String|Array}: File extension or array of extensions.fn
{Function|Object}: oroptions
options
{Object}returns
{Object}Template
: to enable chaining
.getEngine
Get the engine settings registered for the given ext
.
<%= docs("api-getEngine") %>
Params
ext
{String}: The engine to get.returns
{Object}: Object with methods and settings for the specified engine.
Example
template.getEngine('.html');
.helper
Register generic template helpers that can be used with any engine.
Helpers registered using this method will be passed to every
engine, so this method is best for generic javascript functions -
unless you want to see Lo-Dash blow up from Handlebars.SafeString
.
Params
key
{String}: Helper namefn
{Function}: Helper function.
Example
template.helper('lower', function(str) {
return str.toLowerCase();
});
.helpers
Register multiple helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
template.addHelpers({
a: function() {},
b: function() {},
c: function() {},
});
.asyncHelper
Register generic async template helpers that are not specific to an engine.
As with the sync version, helpers registered using this method will be passed to every engine, so this method is best for generic javascript functions.
Params
name
{String}: Helper name.fn
{Function}: Helper function
Example
template.asyncHelper('lower', function(str, next) {
str = str.toLowerCase();
next();
});
.asyncHelpers
Register multiple async helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
template.addAsyncHelpers({
a: function() {},
b: function() {},
c: function() {},
});
.engineHelpers
Register an object of helpers for the given ext
(engine).
Params
ext
{String}: The engine to register helpers with.returns
{Object}: Object of helpers for the specified engine.
Example
template.helpers(require('handlebars-helpers'));
.validate
Validate a template object to ensure that it has the properties expected for applying layouts, choosing engines, and so on.
Params
template
{String}: a template object
.getViews
Get a view collection
by its singular or plural name.
Params
name
{String}: Collection name.returns
{Object}
Example
var pages = template.getViews('pages');
//=> { pages: {'home.hbs': { ... }}
var posts = template.getViews('posts');
//=> { posts: {'2015-10-10.md': { ... }}
.getType
Get all view collections of the given [type].
Params
type
{String}: Types arerenderable
,layout
andpartial
.
Example
var renderable = template.getType('renderable');
//=> { pages: { 'home.hbs': { ... }, 'about.hbs': { ... }}, posts: { ... }}
.mergeType
Merge all collections of the given type
into a single collection. e.g. partials
and includes
would be merged.
If an array of collections
is passed, only those collections
will be merged and the order in which the collections are defined
in the array will be respected.
Params
type
{String}: The template type to search.subtypes
{String}: Optionally pass an array of view collection names
.mergeLayouts
Merge all layout
collections based on user-defined options.
Params
type
{String}: The template type to search.collections
{String}: Optionally pass an array of collections
.mergePartials
Default method for determining how partials are to be passed to engines.
Params
locals
{Object}: Locals should have layout delimiters, if definedreturns
{Object}
Example
template.option('mergePartials', function(locals) {
// do stuff
});
.find
Find the first template that matches the given key
.
Searches all views of [view-subtypes][subtypes] of the given [type], returning
the first template found with the given key
. Optionally pass
an array of subtypes
to limit the search;
Params
type
{String}: The template type to search.key
{String}: The template to find.subtypes
{Array}
Example
template.find('renderable', 'home', ['page', 'post']);
.findRenderable
Search all renderable subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.findLayout
Search all layout subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.findPartial
Search all partial subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.lookup
Convenience method for finding a specific template by name
on
the given collection. Optionally specify a file extension.
Params
plural
{String}: The view collection to search.name
{String}: The name of the template.ext
{String}: Optionally pass a file extension to append toname
.create
Create a new view
collection and associated convience methods.
Note that when you only specify a name for the type, a plural form is created
automatically (e.g. page
and pages
). However, you can define the
plural
form explicitly if necessary.
Params
*
subtype
{String}: Singular name of the collection to create, e.g. page
.
*
plural
{String}: Plural name of the collection, e.g. pages
.
*
options
{Object}: Options for the collection.
isRenderable
{Boolean}: Templates that may be rendered at some pointisLayout
{Boolean}: Templates to be used as layoutsisPartial
{Boolean}: Templates to be used as partial views or includes
*
stack
{Function|Array}: Loader function or functions to be run for every template of this type.
*
returns
{Object} Template
: to enable chaining.
.compileTemplate
Compile content on the given template
object with the specified
engine options
.
Params
template
{Object}: The template object with content to compile.options
{Object}: Options to pass along to the engine when compile. May include acontext
property to bind to helpers.returns
{Object}: Template object to enable chaining.
.compile
Compile content
with the given options
.
Params
file
{Object|String}: String or normalized template object.options
{Object}isAsync
{Boolean}: Load async helpersreturns
{Function}: Compiled function.
.compileString
Compile the given string with the specified options
.
The primary purpose of this method is to get the engine before
passing args to .compileBase
.
Params
str
{String}: The string to compile.options
{Object}: Options to pass to registered view engines.async
{Boolean}: Load async helpersreturns
{Function}
.renderTemplate
Render content on the given template
object with the specified
engine options
and callback
.
Params
template
{Object}: The template object with content to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.render
Render content
with the given options
and optional callback
.
Params
file
{Object|String}: String or normalized template object.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}: Rendered string.
.renderString
Render the given string with the specified locals
and callback
.
The primary purpose of this method is to get the engine before
passing args to .renderBase
.
Params
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.renderSubtype
Returns a render function for rendering templates of the given subtype
.
Mostly used internally as a private method, but it's exposed as a public method since there are cases when it might be useful, like for rendering templates in a gulp/grunt/assemble plugin.
Params
plural
{String}: Template subtype, e.g.pages
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{Function}params
returns
{String}string
: The rendered string.
.renderType
Render the given string with the specified locals
and callback
.
Params
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.renderEach
Render each item in a collection.
Params
collection
{String}: The name of the collection to render.locals
{Object}: Locals object and/or options to pass to the engine as context.returns
{Array}: Array of rendered strings.
Example
template.renderEach('pages', function(err, res) {
//=> array of rendered pages (strings)
});
Render a template
Using the default Lo-Dash engine:
template.render('home.tmpl', function(err, html) {
if (err) throw err;
console.log(html); //=> 'The home page.'
});
Or you can pass a string (non-cached template):
template.render('foo bar', function(err, html) {
if (err) throw err;
console.log(html); //=> 'foo bar'
});
Locals
Pass locals
as the second parameter:
template.render('foo <%= bar %>', {bar: 'baz'}, function(err, html) {
if (err) throw err;
console.log(html); //=> 'foo baz'
});
Register an engine
Register
Examples
// use handlebars to render templates with the `.hbs` extension
template.engine('hbs', require('engine-handlebars'));
// use lo-dash to render templates with the `.tmpl` extension
template.engine('tmpl', require('engine-lodash'));
Using consolidate.js
You can also use consolidate:
var consolidate = require('consolidate');
template.engine('hbs', consolidate.handlebars);
template.engine('tmpl', consolidate.lodash);
Using a custom function
Example of creating an engine to render .less
files:
var less = require('less');
template.engine('less', function(str, options, cb) {
less.render(str, options, function (err, res) {
if (err) { return cb(err); }
cb(null, res.css);
});
});
You can also use engine-less.
Load templates
As glob patterns:
template.pages('pages/*.hbs');
template.pages(['partials/*.hbs', 'includes/*.hbs']);
As key/value pairs:
template.page('home', 'This is home.');
template.page('home', 'This is <%= title %>.', {title: 'home'});
template.page('home', {content: 'This is home.'});
template.page('home', {content: 'This is <%= title %>.', title: 'home'});
template.page('home', {content: 'This is <%= title %>.'}, {title: 'home'});
Note any of the above examples will work with either the singular or plural methods (e.g. page/pages)
Custom templates
Built-in template types are:
page
: the defaultrenderable
template typelayout
: the defaultlayout
template typepartial
: the defaultpartial
template type
If you need something different, add your own:
template.create('post', { isRenderable: true, isPartial: true });
template.create('section', { isLayout: true });
template.create('include', { isPartial: true });
Setting isRenderable
, isLayout
and isPartial
will add special convenience methods to the new template type. For example, when isRenderable
is true, any templates registered for that that type can be rendered directly by passing the name of a template to the .render()
method.
Loading custom templates
We can now load posts using the .post()
or .posts()
methods, the same way that pages or other default templates are loaded:
template.posts('my-blog-post', 'This is content...');
Note: if you create a new template type with a weird plural form, like cactus
, you can pass cacti
as a second arg. e.g. template.create('cactus', 'cactii')
post
will belong to both therenderable
andpartial
types. This means thatposts
can be used as partials, and they will be "findable" on the cache by the render methods. Renderable templates also get their own render methods, but more on that later.section
will belong to thelayout
type. This means that anysection
template can be used as a layout for other templates.include
will belong to thepartial
type. This means that anyinclude
template can be used as partial by other templates.
Custom loaders
Every template subtype uses a built-in loader to load and/or resolve templates. However, if you need something different, just add your own.
Pass an array of functions, each can take any arguments, but the last must pass an object to the callback:
template.create('component', { isPartial: true }, [
function (filepath, next) {
var str = fs.readFileSync(filepath, 'utf8');
var file = {};
file[filepath] = {path: filepath, content: str};
return file;
}]
);
Now, every component
will use this loader.
template.component('components/navbar.html');
//=> {'components/navbar.html': {path: 'components/navbar.html', content: '...'}};
Template-specific loaders
When the last argument passed to a template is an array, or more specifically an array of functions, that array will be concatenated to the loader array for the template's subtype.
Example
template.component('components/navbar.html', [
function(file) {
file.data = file.data || {foo: 'bar'};
return file;
},
function(file) {
file.opts = file.opts || {baz: 'quux'};
return file;
}]
});
//=> {navbar: {path: 'components/navbar.html', content: '...', data: {foo: 'bar'}}};
Loader requirements
As mentioned in the previous section, loader functions may take any arguments long as the last function returns a valid template object.
Valid template object
A valid template object is a key/value pair that looks like this:
// {key: value}
{'foo.txt': {content: 'this is content'}};
key
{String}: the unique identifier for the template. Usually a name or the filepath that was used for loading the templatevalue
{Object}: the actual template object,value
must have the following properties:content
{String}: the string to be rendered
Any additional properties may be added. Useful ones are:
path
{String}: If present, can be used to determine engines, delimiters, etc.ext
{String}: Likepath
, can be used to determine engines, delimiters, etc.options
{Object}: If present, options are passed to engines, and can also be useful in determining engines, delimiters, etc.locals
{Object}: data to pass to templates
API
Template
Create a new instance of Template
, optionally passing default options
to initialize with.
Params
options
{Object}: Options to initialize with.
Example
var Template = require('template');
var template = new Template();
.transform
Assign transform fn
to name
or return the value of name
if no other arguments are passed.
Transforms are run immediately during init, and are used to
extend or modify the cache.data
object, but really anything
on the this
object can be tranformed.
Params
name
{String}: The name of the transform to add.fn
{Function}: The actual transform function.returns
{Object}: ReturnsTemplate
for chaining.
Example
template.transform('username', function(app) {
var url = app.cache.data.author.url.split('/');
app.cache.data.username = url[2];
});
.route
Proxy to the engine Router#route
Returns a new Route
instance for the path
.
Routes are isolated middleware stacks for specific paths.
See the Route
api docs for details.
Params
path
{String}
.param
Proxy to Router#param
with one added api feature. The name
parameter can be an array of names.
See the Router#param
docs for more details.
Params
name
{String|Array}fn
{Function}returns
{Object}Template
: for chaining
Delegate .METHOD(...)
calls to router.METHOD(...)
Params
path
{String}- {Function}: Callback
returns
{Object}Template
: for chaining
.all
Special-cased "all" method, applying the given route path
, middleware, and callback.
Params
path
{String}- {Function}: Callback
returns
{Object}Template
: for chaining
Example
template.all(/\.md$/, function (file, next) {
// do stuff next();
});
.view
Get the given view collection
from views. Optionally
pass a name
to get a specific template from the
collection.
Params
collection
{String}name
{String}returns
{Object}
.engine
<%= docs("api-engine") %>
Register the given view engine callback fn
as ext
. If only ext
is passed, the engine registered for ext
is returned. If no ext
is passed, the entire cache is returned.
Params
exts
{String|Array}: File extension or array of extensions.fn
{Function|Object}: oroptions
options
{Object}returns
{Object}Template
: to enable chaining
.getEngine
Get the engine settings registered for the given ext
.
<%= docs("api-getEngine") %>
Params
ext
{String}: The engine to get.returns
{Object}: Object with methods and settings for the specified engine.
Example
template.getEngine('.html');
.helper
Register generic template helpers that can be used with any engine.
Helpers registered using this method will be passed to every
engine, so this method is best for generic javascript functions -
unless you want to see Lo-Dash blow up from Handlebars.SafeString
.
Params
key
{String}: Helper namefn
{Function}: Helper function.
Example
template.helper('lower', function(str) {
return str.toLowerCase();
});
.helpers
Register multiple helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
template.addHelpers({
a: function() {},
b: function() {},
c: function() {},
});
.asyncHelper
Register generic async template helpers that are not specific to an engine.
As with the sync version, helpers registered using this method will be passed to every engine, so this method is best for generic javascript functions.
Params
name
{String}: Helper name.fn
{Function}: Helper function
Example
template.asyncHelper('lower', function(str, next) {
str = str.toLowerCase();
next();
});
.asyncHelpers
Register multiple async helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
template.addAsyncHelpers({
a: function() {},
b: function() {},
c: function() {},
});
.engineHelpers
Register an object of helpers for the given ext
(engine).
Params
ext
{String}: The engine to register helpers with.returns
{Object}: Object of helpers for the specified engine.
Example
template.helpers(require('handlebars-helpers'));
.validate
Validate a template object to ensure that it has the properties expected for applying layouts, choosing engines, and so on.
Params
template
{String}: a template object
.getViews
Get a view collection
by its singular or plural name.
Params
name
{String}: Collection name.returns
{Object}
Example
var pages = template.getViews('pages');
//=> { pages: {'home.hbs': { ... }}
var posts = template.getViews('posts');
//=> { posts: {'2015-10-10.md': { ... }}
.getType
Get all view collections of the given [type].
Params
type
{String}: Types arerenderable
,layout
andpartial
.
Example
var renderable = template.getType('renderable');
//=> { pages: { 'home.hbs': { ... }, 'about.hbs': { ... }}, posts: { ... }}
.mergeType
Merge all collections of the given type
into a single collection. e.g. partials
and includes
would be merged.
If an array of collections
is passed, only those collections
will be merged and the order in which the collections are defined
in the array will be respected.
Params
type
{String}: The template type to search.subtypes
{String}: Optionally pass an array of view collection names
.mergeLayouts
Merge all layout
collections based on user-defined options.
Params
type
{String}: The template type to search.collections
{String}: Optionally pass an array of collections
.mergePartials
Default method for determining how partials are to be passed to engines.
Params
locals
{Object}: Locals should have layout delimiters, if definedreturns
{Object}
Example
template.option('mergePartials', function(locals) {
// do stuff
});
.find
Find the first template that matches the given key
.
Searches all views of [view-subtypes][subtypes] of the given [type], returning
the first template found with the given key
. Optionally pass
an array of subtypes
to limit the search;
Params
type
{String}: The template type to search.key
{String}: The template to find.subtypes
{Array}
Example
template.find('renderable', 'home', ['page', 'post']);
.findRenderable
Search all renderable subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.findLayout
Search all layout subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.findPartial
Search all partial subtypes
, returning the first template with the given key
.
- If
key
is not foundnull
is returned - Optionally limit the search to the specified
subtypes
.
Params
key
{String}: The template to search for.subtypes
{Array}
.lookup
Convenience method for finding a specific template by name
on
the given collection. Optionally specify a file extension.
Params
plural
{String}: The view collection to search.name
{String}: The name of the template.ext
{String}: Optionally pass a file extension to append toname
.create
Create a new view
collection and associated convience methods.
Note that when you only specify a name for the type, a plural form is created
automatically (e.g. page
and pages
). However, you can define the
plural
form explicitly if necessary.
Params
*
subtype
{String}: Singular name of the collection to create, e.g. page
.
*
plural
{String}: Plural name of the collection, e.g. pages
.
*
options
{Object}: Options for the collection.
isRenderable
{Boolean}: Templates that may be rendered at some pointisLayout
{Boolean}: Templates to be used as layoutsisPartial
{Boolean}: Templates to be used as partial views or includes
*
stack
{Function|Array}: Loader function or functions to be run for every template of this type.
*
returns
{Object} Template
: to enable chaining.
.compileTemplate
Compile content on the given template
object with the specified
engine options
.
Params
template
{Object}: The template object with content to compile.options
{Object}: Options to pass along to the engine when compile. May include acontext
property to bind to helpers.returns
{Object}: Template object to enable chaining.
.compile
Compile content
with the given options
.
Params
file
{Object|String}: String or normalized template object.options
{Object}isAsync
{Boolean}: Load async helpersreturns
{Function}: Compiled function.
.compileString
Compile the given string with the specified options
.
The primary purpose of this method is to get the engine before
passing args to .compileBase
.
Params
str
{String}: The string to compile.options
{Object}: Options to pass to registered view engines.async
{Boolean}: Load async helpersreturns
{Function}
.renderTemplate
Render content on the given template
object with the specified
engine options
and callback
.
Params
template
{Object}: The template object with content to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.render
Render content
with the given options
and optional callback
.
Params
file
{Object|String}: String or normalized template object.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}: Rendered string.
.renderString
Render the given string with the specified locals
and callback
.
The primary purpose of this method is to get the engine before
passing args to .renderBase
.
Params
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.renderSubtype
Returns a render function for rendering templates of the given subtype
.
Mostly used internally as a private method, but it's exposed as a public method since there are cases when it might be useful, like for rendering templates in a gulp/grunt/assemble plugin.
Params
plural
{String}: Template subtype, e.g.pages
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{Function}params
returns
{String}string
: The rendered string.
.renderType
Render the given string with the specified locals
and callback
.
Params
str
{String}: The string to render.locals
{Object}: Locals and/or options to pass to registered view engines.returns
{String}
.renderEach
Render each item in a collection.
Params
collection
{String}: The name of the collection to render.locals
{Object}: Locals object and/or options to pass to the engine as context.returns
{Array}: Array of rendered strings.
Example
template.renderEach('pages', function(err, res) {
//=> array of rendered pages (strings)
});
Additional docs
Related
Libraries that are used in Template:
- async: Higher-order functions and common patterns for asynchronous code
- config-cache: General purpose JavaScript object storage methods.
- en-route: Routing for static site generators, build systems and task runners, heavily based on express.js routes… more
- engine-cache: express.js inspired template-engine manager.
- helper-cache: Easily register and get helper functions to be passed to any template engine or node.js… more
- layouts: Wrap templates with layouts. Layouts can be nested and optionally use other layouts.
- loader-cache: Register loader functions that dynamically read, parse or otherwise transform file contents when the name… more
Running tests
Install dev dependencies:
npm i -d && npm test
Build docs
Install devDependencies:
npm i -d && verb
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue
Authors
Jon Schlinkert
License
Copyright (c) 2014-2015 Jon Schlinkert Released under the MIT license.
This file was generated by verb-cli on May 10, 2015.