Package Exports
- templates
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 (templates) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
templates 
System for creating and managing template collections, and rendering templates with any node.js template engine. Can be used as the basis for creating a static site generator or blog framework.
Features
- create custom view collections using
app.create('foo')
- register any template engine for rendering views
- register helpers
- partial support
- plugins and middleware
Example
This is just a very small glimpse at the templates
API!
var templates = require('templates');
var app = templates();
// create a collection
app.create('pages');
// add views to the collection
app.page('a.html', {content: 'this is <%= foo %>'});
app.page('b.html', {content: 'this is <%= bar %>'});
app.page('c.html', {content: 'this is <%= baz %>'});
app.pages.getView('a.html')
.render({foo: 'home'}, function (err, view) {
//=> 'this is home'
});
Table of contents
(Table of contents generated by [verb])
Install
Install with npm
$ npm i templates --save
Usage
var templates = require('templates');
var app = templates();
API
Templates
This function is the main export of the templates module. Initialize an instance of templates
to create your application.
Params
options
{Object}
Example
var templates = require('templates');
var app = templates();
.use
Run a plugin on the instance. Plugins are invoked immediately upon creating the collection in the order in which they were defined.
Params
fn
{Function}: Plugin function. If the plugin returns a function it will be passed to theuse
method of each collection created on the instance.returns
{Object}: Returns the instance for chaining.
Example
var app = templates()
.use(require('foo'))
.use(require('bar'))
.use(require('baz'))
.view
Returns a new view, using the View
class currently defined on the instance.
Params
key
{String|Object}: View key or objectvalue
{Object}: If key is a string, value is the view object.returns
{Object}: returns theview
object
Example
var view = app.view('foo', {conetent: '...'});
// or
var view = app.view({path: 'foo', conetent: '...'});
.item
Returns a new item, using the Item
class currently defined on the instance.
Params
key
{String|Object}: Item key or objectvalue
{Object}: If key is a string, value is the item object.returns
{Object}: returns theitem
object
Example
var item = app.item('foo', {conetent: '...'});
// or
var item = app.item({path: 'foo', conetent: '...'});
.collection
Create a new collection. Collections are decorated with special methods for getting and setting items from the collection. Note that, unlike the create method, collections created with .collection()
are not cached.
See the collection docs for more information about collections.
Params
opts
{Object}: Collection optionsreturns
{Object}: Returns thecollection
instance for chaining.
.viewCollection
Create a new view collection. View collections are decorated with special methods for getting, setting and rendering views from that collection. Collections created with this method are not stored on app.views
as with the create method.
See the collection docs for more information about view collections.
Params
opts
{Object}: View collection options.returns
{Object}: Returns the view collection instance for chaining.
.create
Create a new view collection to be stored on the app.views
object. See
the create docs for more details.
Params
name
{String}: The name of the collection to create. Plural or singular form may be used, as the inflections are automatically resolved when the collection is created.opts
{Object}: Collection optionsreturns
{Object}: Returns thecollection
instance for chaining.
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
app.option('a', 'b');
app.option({c: 'd'});
console.log(app.options);
//=> {a: 'b', c: 'd'}
Engines
.engine
Register a view engine callback fn
as ext
.
Params
exts
{String|Array}: String or array of file extensions.fn
{Function|Object}: orsettings
settings
{Object}: Optionally pass engine options as the last argument.
Example
app.engine('hbs', require('engine-handlebars'));
// using consolidate.js
var engine = require('consolidate');
app.engine('jade', engine.jade);
app.engine('swig', engine.swig);
// get a registered engine
var swig = app.engine('swig');
Helpers
.helper
Register a template helper.
Params
name
{String}: Helper namefn
{Function}: Helper function.
Example
app.helper('upper', function(str) {
return str.toUpperCase();
});
.helpers
Register multiple template helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
app.helpers({
foo: function() {},
bar: function() {},
baz: function() {}
});
.asyncHelper
Get or set an async helper. If only the name is passed, the helper is returned.
Params
name
{String}: Helper name.fn
{Function}: Helper function
Example
app.asyncHelper('upper', function(str, next) {
next(null, str.toUpperCase());
});
.asyncHelper
Register multiple async template helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
app.asyncHelpers({
foo: function() {},
bar: function() {},
baz: function() {}
});
.helperGroup
Register a namespaced helper group.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
// markdown-utils
app.helperGroup('mdu', {
reflink: function() {},
link: function() {},
});
//=> <%%= mdu.link() %>
View
View
Create an instance of View
. Optionally pass a default object to use.
Params
view
{Object}
Example
var view = new View({
path: 'foo.html',
content: '...'
});
.compile
Synchronously compile a view.
Params
locals
{Object}: Optionally pass locals to the engine.returns
{Object}View
: instance, for chaining.
Example
var view = page.compile();
view.fn({title: 'A'});
view.fn({title: 'B'});
view.fn({title: 'C'});
.render
Asynchronously render a view.
Params
locals
{Object}: Optionally pass locals to the engine.returns
{Object}View
: instance, for chaining.
Example
view.render({title: 'Home'}, function(err, res) {
//=> view object with rendered `content`
});
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
view.option('a', 'b');
view.option({c: 'd'});
console.log(view.options);
//=> {a: 'b', c: 'd'}
Data
.data
Set, get and load data to be passed to templates as context at render-time.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
view.data('a', 'b');
view.data({c: 'd'});
console.log(view.cache.data);
//=> {a: 'b', c: 'd'}
.mergePartials
Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.
Params
options
{Object}: Optionally pass an array ofviewTypes
to include onoptions.viewTypes
returns
{Object}: Merged partials
Item
Item
Create an instance of Item
. Optionally pass a default object to use.
Params
item
{Object}
Example
var item = new Item({
path: 'foo.html',
content: '...'
});
.use
Run a plugin on the item
instance.
Params
fn
{Function}returns
{Object}
Example
var item = new Item({path: 'abc', contents: '...'})
.use(require('foo'))
.use(require('bar'))
.use(require('baz'))
.clone
Re-decorate Item methods after calling vinyl's .clone()
method.
Params
options
{Object}returns
{Object}item
: Cloned instance
Example
item.clone({deep: true}); // false by default
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
item.option('a', 'b');
item.option({c: 'd'});
console.log(item.options);
//=> {a: 'b', c: 'd'}
Data
.data
Set, get and load data to be passed to templates as context at render-time.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
item.data('a', 'b');
item.data({c: 'd'});
console.log(item.cache.data);
//=> {a: 'b', c: 'd'}
.mergePartials
Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.
Params
options
{Object}: Optionally pass an array ofviewTypes
to include onoptions.viewTypes
returns
{Object}: Merged partials
Collections
Collection
Create an instance of Collection
with the given options
.
Params
options
{Object}
Example
var collection = new Collection();
collection.addItem('foo', {content: 'bar'});
.use
Run a plugin on the collection instance. Plugins are invoked immediately upon creating the collection in the order in which they were defined.
Params
fn
{Function}: Plugin function. If the plugin returns a function it will be passed to theuse
method of each item created on the instance.returns
{Object}: Returns the instance for chaining.
Example
collection.use(function(items) {
// `items` is the instance, as is `this`
// optionally return a function to be passed to
// the `.use` method of each item created on the
// instance
return function(item) {
// do stuff to each `item`
};
});
.item
Returns a new item, using the Item
class currently defined on the instance.
Params
key
{String|Object}: Item key or objectvalue
{Object}: If key is a string, value is the item object.returns
{Object}: returns theitem
object
Example
var item = app.item('foo', {conetent: '...'});
// or
var item = app.item({path: 'foo', conetent: '...'});
.setItem
Set an item on the collection. This is identical to addItem except setItem
does not emit an event for each item.
Params
key
{String|Object}: Item key or objectvalue
{Object}: If key is a string, value is the item object.returns
{Object}: returns theitem
instance.
Example
collection.setItem('foo', {content: 'bar'});
.addItem
Adds event emitting and custom loading to setItem.
Params
key
{String}value
{Object}
.addItems
Load multiple items onto the collection.
Params
items
{Object|Array}returns
{Object}: returns thecollection
object
Example
collection.addItems({
'a.html': {content: '...'},
'b.html': {content: '...'},
'c.html': {content: '...'}
});
.addList
Load an array of items onto the collection.
Params
items
{Array}returns
{Object}: returns thecollection
instance
Example
collection.addList([
{path: 'a.html', content: '...'},
{path: 'b.html', content: '...'},
{path: 'c.html', content: '...'}
]);
.getItem
Get an item from the collection.
Params
key
{String}: Key of the item to get.returns
{Object}
Example
collection.getItem('a.html');
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
collection.option('a', 'b');
collection.option({c: 'd'});
console.log(collection.options);
//=> {a: 'b', c: 'd'}
Data
.data
Set, get and load data to be passed to templates as context at render-time.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
collection.data('a', 'b');
collection.data({c: 'd'});
console.log(collection.cache.data);
//=> {a: 'b', c: 'd'}
.mergePartials
Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.
Params
options
{Object}: Optionally pass an array ofviewTypes
to include onoptions.viewTypes
returns
{Object}: Merged partials
View collections
Views
Create an instance of Views
with the given options
.
Params
options
{Object}
Example
var collection = new Views();
collection.addView('foo', {content: 'bar'});
.use
Run a plugin on the collection instance. Plugins are invoked immediately upon creating the collection in the order in which they were defined.
Params
fn
{Function}: Plugin function. If the plugin returns a function it will be passed to theuse
method of each view created on the instance.returns
{Object}: Returns the instance for chaining.
Example
collection.use(function(views) {
// `views` is the instance, as is `this`
// optionally return a function to be passed to
// the `.use` method of each view created on the
// instance
return function(view) {
// do stuff to each `view`
};
});
.view
Returns a new view, using the View
class currently defined on the instance.
Params
key
{String|Object}: View key or objectvalue
{Object}: If key is a string, value is the view object.returns
{Object}: returns theview
object
Example
var view = app.view('foo', {conetent: '...'});
// or
var view = app.view({path: 'foo', conetent: '...'});
.setView
Set a view on the collection. This is identical to addView except setView
does not emit an event for each view.
Params
key
{String|Object}: View key or objectvalue
{Object}: If key is a string, value is the view object.returns
{Object}: returns theview
instance.
Example
collection.setView('foo', {content: 'bar'});
.addView
Adds event emitting and custom loading to setView.
Params
key
{String}value
{Object}
.addViews
Load multiple views onto the collection.
Params
views
{Object|Array}returns
{Object}: returns thecollection
object
Example
collection.addViews({
'a.html': {content: '...'},
'b.html': {content: '...'},
'c.html': {content: '...'}
});
.addList
Load an array of views onto the collection.
Params
list
{Array}returns
{Object}: returns theviews
instance
Example
collection.addList([
{path: 'a.html', content: '...'},
{path: 'b.html', content: '...'},
{path: 'c.html', content: '...'}
]);
.loadView
Loads and create a new View
from the file system.
Params
filename
{String}options
{Object}returns
{Object}: Returns view object
.getView
Get a view from the collection.
Params
key
{String}: Key of the view to get.returns
{Object}
Example
collection.getView('a.html');
.extendView
Decorate each view on the collection with additional methods and properties. This provides a way of easily overriding defaults.
Params
view
{Object}returns
{Object}
Helpers
The following methods are available on view collections as well as the main application instance. Note that when helpers are registered on a specific view collection, they will only be available to views in that collection.
.helper
Register a template helper.
Params
name
{String}: Helper namefn
{Function}: Helper function.
Example
pages.helper('upper', function(str) {
return str.toUpperCase();
});
.helpers
Register multiple template helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
pages.helpers({
foo: function() {},
bar: function() {},
baz: function() {}
});
.asyncHelper
Get or set an async helper. If only the name is passed, the helper is returned.
Params
name
{String}: Helper name.fn
{Function}: Helper function
Example
pages.asyncHelper('upper', function(str, next) {
next(null, str.toUpperCase());
});
.asyncHelper
Register multiple async template helpers.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
pages.asyncHelpers({
foo: function() {},
bar: function() {},
baz: function() {}
});
.helperGroup
Register a namespaced helper group.
Params
helpers
{Object|Array}: Object, array of objects, or glob patterns.
Example
// markdown-utils
pages.helperGroup('mdu', {
reflink: function() {},
link: function() {},
});
//=> <%%= mdu.link() %>
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
viewCollection.option('a', 'b');
viewCollection.option({c: 'd'});
console.log(viewCollection.options);
//=> {a: 'b', c: 'd'}
Data
.data
Set, get and load data to be passed to templates as context at render-time.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
viewCollection.data('a', 'b');
viewCollection.data({c: 'd'});
console.log(viewCollection.cache.data);
//=> {a: 'b', c: 'd'}
.mergePartials
Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.
Params
options
{Object}: Optionally pass an array ofviewTypes
to include onoptions.viewTypes
returns
{Object}: Merged partials
List
.use
Run a plugin on the list instance. Plugins are invoked immediately upon creating the list in the order in which they were defined.
Params
fn
{Function}: Plugin function. If the plugin returns a function it will be passed to theuse
method of each view created on the instance.returns
{Object}: Returns the instance for chaining.
Example
list.use(function(views) {
// `views` is the instance, as is `this`
// optionally return a function to be passed to
// the `.use` method of each view created on the
// instance
return function(view) {
// do stuff to each `view`
};
});
.item
Returns a new item, using the Item
class currently defined on the instance.
Params
key
{String|Object}: Item key or objectvalue
{Object}: If key is a string, value is the item object.returns
{Object}: returns theitem
object
Example
var item = app.item('foo', {conetent: '...'});
// or
var item = app.item({path: 'foo', conetent: '...'});
.setItem
Set an item on the collection. This is identical to addItem except setItem
does not emit an event for each item.
Params
key
{String|Object}: Item key or objectvalue
{Object}: If key is a string, value is the item object.returns
{Object}: returns theitem
instance.
Example
collection.setItem('foo', {content: 'bar'});
Adds event emitting and custom loading to setItem.
Params
key
{String}value
{Object}
.addItem
Add an item to the list. An item may be an instance of Item
, and if not the item is converted to an instance of Item
.
Params
items
{Object}: Object of views
Example
var list = new List(...);
list.addItem('a.html', {path: 'a.html', contents: '...'});
.addItems
Add an object of views
to the list.
Params
items
{Object}: Object of views
Example
var list = new List(...);
list.addItems({
'a.html': {path: 'a.html', contents: '...'}
});
.addList
Add the items from another instance of List
.
Params
list
{Array}: Instance ofList
fn
{Function}: Optional sync callback function that is called on each item.
Example
var foo = new List(...);
var bar = new List(...);
bar.addList(foo);
.getIndex
Get a the index of a specific item from the list by key
.
Params
key
{String}returns
{Object}
Example
list.getIndex('foo.html');
//=> 1
.getItem
Get a specific item from the list by key
.
Params
key
{String}returns
{Object}
Example
list.getItem('foo.html');
//=> '<View <foo.html>>'
.removeItem
Remove an item from the list.
Params
items
{Object}: Object of views
Example
var list = new List(...);
list.addItems({
'a.html': {path: 'a.html', contents: '...'}
});
.groupBy
Group all list items
using the given property, properties or compare functions. See [group-array][] for the full range of available features and options.
returns
{Object}: Returns the grouped items.
Example
var list = new List();
list.addItems(...);
var groups = list.groupBy('data.date', 'data.slug');
.sortBy
Sort all list items
using the given property, properties or compare functions. See [array-sort][] for the full range of available features and options.
returns
{Object}: Returns a newList
instance with sorted items.
Example
var list = new List();
list.addItems(...);
var result = list.sortBy('data.date');
//=> new sorted list
.paginate
Paginate all items
in the list with the given options, See [paginationator][] for the full range of available features and options.
returns
{Object}: Returns the paginated items.
Example
var list = new List(items);
var pages = list.paginate({limit: 5});
Settings
.option
Set or get an option value.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
list.option('a', 'b');
list.option({c: 'd'});
console.log(list.options);
//=> {a: 'b', c: 'd'}
Group
Group
Create an instance of Group
with the given options
.
Params
options
{Object}
Example
var group = new Group({
'foo': {
items: [1,2,3]
}
});
.use
Run a plugin on the group instance. Plugins are invoked immediately upon creating the group in the order in which they were defined.
Params
fn
{Function}: Plugin function.returns
{Object}: Returns the instance for chaining.
Example
group.use(function(group) {
// `group` is the instance, as is `this`
});
Lookups
.find
Find a view by name
, optionally passing a collection
to limit the search. If no collection is passed all renderable
collections will be searched.
Params
name
{String}: The name/key of the view to findcolleciton
{String}: Optionally pass a collection name (e.g. pages)returns
{Object|undefined}: Returns the view if found, orundefined
if not.
Example
var page = app.find('my-page.hbs');
// optionally pass a collection name as the second argument
var page = app.find('my-page.hbs', 'pages');
.getView
Get view key
from the specified collection
.
Params
collection
{String}: Collection name, e.g.pages
key
{String}: Template namefn
{Function}: Optionally pass arenameKey
functionreturns
{Object}
Example
var view = app.getView('pages', 'a/b/c.hbs');
// optionally pass a `renameKey` function to modify the lookup
var view = app.getView('pages', 'a/b/c.hbs', function(fp) {
return path.basename(fp);
});
.getViews
Get all views from a collection
using the collection's singular or plural name.
Params
name
{String}: The collection name, e.g.pages
orpage
returns
{Object}
Example
var pages = app.getViews('pages');
//=> { pages: {'home.hbs': { ... }}
var posts = app.getViews('posts');
//=> { posts: {'2015-10-10.md': { ... }}
Rendering
.compile
Compile content
with the given locals
.
Params
view
{Object|String}: View object.locals
{Object}isAsync
{Boolean}: Load async helpersreturns
{Object}: View object withfn
property with the compiled function.
Example
var indexPage = app.page('some-index-page.hbs');
var view = app.compile(indexPage);
// view.fn => [function]
// you can call the compiled function more than once
// to render the view with different data
view.fn({title: 'Foo'});
view.fn({title: 'Bar'});
view.fn({title: 'Baz'});
.render
Render a view with the given locals
and callback
.
Params
view
{Object|String}: Instance ofView
locals
{Object}: Locals to pass to template engine.callback
{Function}
Example
var blogPost = app.post.getView('2015-09-01-foo-bar');
app.render(blogPost, {title: 'Foo'}, function(err, view) {
// `view` is an object with a rendered `content` property
});
Context
.data
Set, get and load data to be passed to templates as context at render-time.
Params
key
{String|Object}: Pass a key-value pair or an object to set.val
{any}: Any value when a key-value pair is passed. This can also be options if a glob pattern is passed as the first value.returns
{Object}: Returns an instance ofTemplates
for chaining.
Example
app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}
.mergePartials
Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.
Params
options
{Object}: Optionally pass an array ofviewTypes
to include onoptions.viewTypes
returns
{Object}: Merged partials
Routes and middleware
.handle
Handle a middleware method
for view
.
Params
method
{String}: Name of the router method to handle. See router methodsview
{Object}: View objectcallback
{Function}: Callback functionreturns
{Object}
Example
app.handle('customMethod', view, callback);
.route
Create a new Route for the given path. Each route contains a separate middleware stack.
See the [route API documentation][route-api] for details on adding handlers and middleware to routes.
Params
path
{String}returns
{Object}Route
: for chaining
Example
app.create('posts');
app.route(/blog/)
.all(function(view, next) {
// do something with view
next();
});
app.post('whatever', {path: 'blog/foo.bar', content: 'bar baz'});
.all
Special route method that works just like the router.METHOD()
methods, except that it matches all verbs.
Params
path
{String}callback
{Function}returns
{Object}this
: for chaining
Example
app.all(/\.hbs$/, function(view, next) {
// do stuff to view
next();
});
.param
Add callback triggers to route parameters, where name
is the name of the parameter and fn
is the callback function.
Params
name
{String}fn
{Function}returns
{Object}: Returns the instance ofTemplates
for chaining.
Example
app.param('title', function (view, next, title) {
//=> title === 'foo.js'
next();
});
app.onLoad('/blog/:title', function (view, next) {
//=> view.path === '/blog/foo.js'
next();
});
Related projects
{%= related(verb.related.list, {remove: name}) %}
Running tests
Install dev dependencies:
$ npm i -d && npm test
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
If this project doesn't do what you need, please let us know.
Author
Jon Schlinkert
License
Copyright © 2015 Jon Schlinkert Released under the MIT license.
This file was generated by verb-cli on September 22, 2015.
{%= reflinks(verb.related.list.concat(['micromatch', 'group-array', 'array-sort', 'paginationator'])) %}