Home

Awesome

templates NPM version NPM monthly downloads NPM total downloads Linux Build Status Windows Build Status

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.

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm:

$ npm install --save templates

Features

Usage

var templates = require('templates');
var app = templates();

Example

// register an engine to automatically render `md` files
app.engine('md', require('engine-lodash'));

// create a template collection
app.create('pages');

// add a template to the collection
app.page('post.md', {content: 'This is the <%= title %> page'});

// render it
app.render('post.md', {title: 'Home'}, function(err, view) {
  console.log(view.content);
  //=> 'This is the Home page'
});

API

Common

This section describes API features that are shared by all Templates classes.

.option

Set or get an option value.

Params

Example

app.option('a', 'b');
app.option({c: 'd'});
console.log(app.options);
//=> {a: 'b', c: 'd'}

.use

Run a plugin on the given instance. Plugins are invoked immediately upon instantiating in the order in which they were defined.

Example

The simplest plugin looks something like the following:

app.use(function(inst) {
  // do something to `inst`
});

Note that inst is the instance of the class you're instantiating. So if you create an instance of Collection, inst is the collection instance.

Params

Usage

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`
  };
});

App

The Templates class is the main export of the templates library. All of the other classes are exposed as static properties on Templates:

Templates

This function is the main export of the templates module. Initialize an instance of templates to create your application.

Params

Example

var templates = require('templates');
var app = templates();

.list

Create a new list. See the list docs for more information about lists.

Params

Example

var list = app.list();
list.addItem('abc', {content: '...'});

// or, create list from a collection
app.create('pages');
var list = app.list(app.pages);

.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

.create

Create a new view collection to be stored on the app.views object. See the create docs for more details.

Params

.setup

Expose static setup method for providing access to an instance before any other code is run.

Params

Example

function App(options) {
  Templates.call(this, options);
  Templates.setup(this);
}
Templates.extend(App);

.engine

Register a view engine callback fn as ext. Calls .setEngine and .getEngine internally.

Params

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');

.setEngine

Register engine ext with the given render fn and/or settings.

Params

Example

app.setEngine('hbs', require('engine-handlebars'), {
  delims: ['<%', '%>']
});

.getEngine

Get registered engine ext.

Params

Example

app.engine('hbs', require('engine-handlebars'));
var engine = app.getEngine('hbs');

.helper

Register a template helper.

Params

Example

app.helper('upper', function(str) {
  return str.toUpperCase();
});

.helpers

Register multiple template helpers.

Params

Example

app.helpers({
  foo: function() {},
  bar: function() {},
  baz: function() {}
});

.asyncHelper

Register an async helper.

Params

Example

app.asyncHelper('upper', function(str, next) {
  next(null, str.toUpperCase());
});

.asyncHelpers

Register multiple async template helpers.

Params

Example

app.asyncHelpers({
  foo: function() {},
  bar: function() {},
  baz: function() {}
});

.getHelper

Get a previously registered helper.

Params

Example

var fn = app.getHelper('foo');

.getAsyncHelper

Get a previously registered async helper.

Params

Example

var fn = app.getAsyncHelper('foo');

.hasHelper

Return true if sync helper name is registered.

Params

Example

if (app.hasHelper('foo')) {
  // do stuff
}

.hasAsyncHelper

Return true if async helper name is registered.

Params

Example

if (app.hasAsyncHelper('foo')) {
  // do stuff
}

.helperGroup

Register a namespaced helper group.

Params

Example

// markdown-utils
app.helperGroup('mdu', {
  foo: function() {},
  bar: function() {},
});

// Usage:
// <%= mdu.foo() %>
// <%= mdu.bar() %>

Built-in helpers


View

API for the View class.

View

Create an instance of View. Optionally pass a default object to use.

Params

Example

var view = new View({
  path: 'foo.html',
  contents: new Buffer('...')
});

.compile

Synchronously compile a view.

Params

Example

var view = page.compile();
view.fn({title: 'A'});
view.fn({title: 'B'});
view.fn({title: 'C'});

.renderSync

Synchronously render templates in view.content.

Params

Example

var view = new View({content: 'This is <%= title %>'});
view.renderSync({title: 'Home'});
console.log(view.content);

.render

Asynchronously render templates in view.content.

Params

Example

view.render({title: 'Home'}, function(err, res) {
  //=> view object with rendered `content`
});

.context

Create a context object from locals and the view.data and view.locals objects. The view.data property is typically created from front-matter, and view.locals is used when a new View() is created.

This method be overridden either by defining a custom view.options.context function to customize context for a view instance, or static View.context function to customize context for all view instances.

Params

Example

var page = new View({path: 'a/b/c.txt', locals: {a: 'b', c: 'd'}});
var ctx = page.context({a: 'z'});
console.log(ctx);
//=> {a: 'z', c: 'd'}

.isType

Returns true if the view is the given viewType. Returns false if no type is assigned. When used with vinyl-collections, types are assigned by their respective collections.

Params

Example

var view = new View({path: 'a/b/c.txt', viewType: 'partial'})
view.isType('partial');

.View.context

Define a custom static View.context function to override default .context behavior. See the context docs for more info.

Params

Example

// custom context function
View.context = function(locals) {
  // `this` is the view being rendered
  return locals;
};

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


Item

API for the Item class.

Item

Create an instance of Item. Optionally pass a default object to use. See vinyl docs for API details and additional documentation.

Params

Example

var item = new Item({
  path: 'foo.html',
  contents: new Buffer('...')
});

.content

Normalize the content and contents properties on item. This is done to ensure compatibility with the vinyl convention of using contents as a Buffer, as well as the assemble convention of using content as a string. We will eventually deprecate the content property.

Example

var item = new Item({path: 'foo/bar.hbs', contents: new Buffer('foo')});
console.log(item.content);
//=> 'foo'

.engine

Getter/setter to resolve the name of the engine to use for rendering.

Example

var item = new Item({path: 'foo/bar.hbs'});
console.log(item.engine);
//=> '.hbs'

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


Views

API for the Views class.

Views

Create an instance of Views with the given options.

Params

Example

var collection = new Views();
collection.addView('foo', {content: 'bar'});

.addView

Add a view to collection.views. This is identical to addView except setView returns the collection instance, and addView returns the item instance.

Params

Example

collection.setView('foo', {content: 'bar'});

// or, optionally async
collection.setView('foo', {content: 'bar'}, function(err, view) {
  // `err` errors from `onLoad` middleware
  // `view` the view object after `onLoad` middleware has run
});

.setView

Set a view on the collection. This is identical to addView except setView does not emit an event for each view.

Params

Example

collection.setView('foo', {content: 'bar'});

.getView

Get view name from collection.views.

Params

Example

collection.getView('a.html');

.deleteView

Delete a view from collection views.

Params

Example

views.deleteView('foo.html');

.addViews

Load multiple views onto the collection.

Params

Example

collection.addViews({
  'a.html': {content: '...'},
  'b.html': {content: '...'},
  'c.html': {content: '...'}
});

.addList

Load an array of views onto the collection.

Params

Example

collection.addList([
  {path: 'a.html', content: '...'},
  {path: 'b.html', content: '...'},
  {path: 'c.html', content: '...'}
]);

.groupBy

Group all collection views by the given property, properties or compare functions. See group-array for the full range of available features and options.

Example

var collection = new Collection();
collection.addViews(...);
var groups = collection.groupBy('data.date', 'data.slug');

.isType

Return true if the collection belongs to the given view type.

Params

Example

collection.isType('partial');

.viewTypes

Alias for viewType

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


.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

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

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

Example

var pages = app.getViews('pages');
//=> { pages: {'home.hbs': { ... }}

var posts = app.getViews('posts');
//=> { posts: {'2015-10-10.md': { ... }}

Collections

API for the Collections class.

Collection

Create an instance of Collection with the given options.

Params

Example

var collection = new Collection();
collection.addItem('foo', {content: 'bar'});

.addItem

Add an item to the collection.

Params

Events

Example

collection.addItem('foo', {content: 'bar'});

.setItem

Identical to .addItem, except the collection instance is returned instead of the item, to allow chaining.

Params

Events

Example

collection.setItem('foo', {content: 'bar'});

.getItem

Get an item from collection.items.

Params

Example

collection.getItem('a.html');

.deleteItem

Remove an item from collection.items.

Params

Example

items.deleteItem('abc');

.addItems

Load multiple items onto the collection.

Params

Example

collection.addItems({
  'a.html': {content: '...'},
  'b.html': {content: '...'},
  'c.html': {content: '...'}
});

.addList

Load an array of items onto the collection.

Params

Example

collection.addList([
  {path: 'a.html', content: '...'},
  {path: 'b.html', content: '...'},
  {path: 'c.html', content: '...'}
]);

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


List

API for the List class.

List

Create an instance of List with the given options. Lists differ from collections in that items are stored as an array, allowing items to be paginated, sorted, and grouped.

Params

Example

var list = new List();
list.addItem('foo', {content: 'bar'});

.addItem

Add an item to list.items. This is identical to setItem except addItem returns the item, add setItem returns the instance of List.

Params

Example

collection.addItem('foo', {content: 'bar'});

.setItem

Add an item to list.items. This is identical to addItem except addItem returns the item, add setItem returns the instance of List.

Params

Example

var items = new Items(...);
items.setItem('a.html', {path: 'a.html', contents: '...'});

.addItems

Load multiple items onto the collection.

Params

Example

collection.addItems({
  'a.html': {content: '...'},
  'b.html': {content: '...'},
  'c.html': {content: '...'}
});

.addList

Load an array of items or the items from another instance of List.

Params

Example

var foo = new List(...);
var bar = new List(...);
bar.addList(foo);

.hasItem

Return true if the list has the given item (name).

Params

Example

list.addItem('foo.html', {content: '...'});
list.hasItem('foo.html');
//=> true

.getIndex

Get a the index of a specific item from the list by key.

Params

Example

list.getIndex('foo.html');
//=> 1

.getItem

Get a specific item from the list by key.

Params

Example

list.getItem('foo.html');
//=> '<Item <foo.html>>'

.getView

Proxy for getItem

Params

Example

list.getItem('foo.html');
//=> '<Item "foo.html" <buffer e2 e2 e2>>'

.deleteItem

Remove an item from the list.

Params

Example

list.deleteItem('a.html');

.deleteItems

Remove one or more items from the list.

Params

Example

list.deleteItems(['a.html', 'b.html']);

.extendItem

Decorate each item on the list with additional methods and properties. This provides a way of easily overriding defaults.

Params

.filter

Filters list items using the given fn and returns a new array.

Example

var items = list.filter(function(item) {
  return item.data.title.toLowerCase() !== 'home';
});

.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.

Example

var list = new List();
list.addItems(...);
var result = list.sortBy('data.date');
//=> new sorted list

.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.

Example

var list = new List();
list.addItems(...);
var groups = list.groupBy('data.date', 'data.slug');

.paginate

Paginate all items in the list with the given options, See paginationator for the full range of available features and options.

Example

var list = new List(items);
var pages = list.paginate({limit: 5});

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


Group

API for the Group class.

Group

Create an instance of Group with the given options.

Params

Example

var group = new Group({
  'foo': { items: [1,2,3] }
});

.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

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

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

Example

var pages = app.getViews('pages');
//=> { pages: {'home.hbs': { ... }}

var posts = app.getViews('posts');
//=> { posts: {'2015-10-10.md': { ... }}

.compile

Compile content with the given locals.

Params

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'});

.compileAsync

Asynchronously compile content with the given locals and callback. (fwiw, this method name uses the unconventional "*Async" nomenclature to allow us to preserve the synchronous behavior of the view.compile method as well as the name).

Params

Example

var indexPage = app.page('some-index-page.hbs');
app.compileAsync(indexPage, function(err, view) {
  // view.fn => compiled function
});

.render

Render a view with the given locals and callback.

Params

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
});

.data

Set, get and load data to be passed to templates as context at render-time.

Params

Example

app.data('a', 'b');
app.data({c: 'd'});
console.log(app.cache.data);
//=> {a: 'b', c: 'd'}

.context

Build the context for the given view and locals.

Params

setHelperOptions

Update context in a helper so that this.helper.options is the options for that specific helper.

Params

.mergePartials

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params

.mergePartialsAsync

Merge "partials" view types. This is necessary for template engines have no support for partials or only support one type of partials.

Params


Middleware

Control the entire render cycle, with simple-to-use routes and middleware.

Example

var router = new app.Router();
var route = new app.Route();

.handle

Handle a middleware method for file.

Params

Example

app.handle('customMethod', file, callback);

.handleOnce

Run the given middleware handler only if the file has not already been handled by method.

Params

Example

app.handleOnce('onLoad', file, 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

Example

app.create('posts');
app.route(/blog/)
  .all(function(file, next) {
    // do something with file
    next();
  });

app.post('whatever', {path: 'blog/foo.bar', content: 'bar baz'});

.param

Add callback triggers to route parameters, where name is the name of the parameter and fn is the callback function.

Params

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();
});

.all

Special route method that works just like the router.METHOD() methods, except that it matches all verbs.

Params

Example

app.all(/\.hbs$/, function(view, next) {
  // do stuff to view
  next();
});

.handler

Add a router handler method to the instance. Interchangeable with the handlers method.

Params

Example

app.handler('onFoo');
// or
app.handler(['onFoo', 'onBar']);

.handlers

Add one or more router handler methods to the instance.

Params

Example

app.handlers(['onFoo', 'onBar', 'onBaz']);
// or
app.handlers('onFoo');

.isApp

Static method that returns true if the given value is a templates instance (App).

Params

Example

var templates = require('templates');
var app = templates();

templates.isApp(templates);
//=> false

templates.isApp(app);
//=> true

.isCollection

Static method that returns true if the given value is a templates Collection instance.

Params

Example

var templates = require('templates');
var app = templates();

app.create('pages');
templates.isCollection(app.pages);
//=> true

.isViews

Static method that returns true if the given value is a templates Views instance.

Params

Example

var templates = require('templates');
var app = templates();

app.create('pages');
templates.isViews(app.pages);
//=> true

.isList

Static method that returns true if the given value is a templates List instance.

Params

Example

var templates = require('templates');
var List = templates.List;
var app = templates();

var list = new List();
templates.isList(list);
//=> true

.isGroup

Static method that returns true if the given value is a templates Group instance.

Params

Example

var templates = require('templates');
var Group = templates.Group;
var app = templates();

var group = new Group();
templates.isGroup(group);
//=> true

.isView

Static method that returns true if the given value is a templates View instance.

Params

Example

var templates = require('templates');
var app = templates();

templates.isView('foo');
//=> false

var view = app.view('foo', {content: '...'});
templates.isView(view);
//=> true

.isItem

Static method that returns true if the given value is a templates Item instance.

Params

Example

var templates = require('templates');
var app = templates();

templates.isItem('foo');
//=> false

var view = app.view('foo', {content: '...'});
templates.isItem(view);
//=> true

.isVinyl

Static method that returns true if the given value is a vinyl File instance.

Params

Example

var File = require('vinyl');
var templates = require('templates');
var app = templates();

var view = app.view('foo', {content: '...'});
templates.isVinyl(view);
//=> true

var file = new File({path: 'foo', contents: new Buffer('...')});
templates.isVinyl(file);
//=> true

More examples

This is just a very basic 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'
  });

History

key

Starting with v0.25.0, changelog entries will be categorized using the following labels from keep-a-changelog_:

1.1.0

fixed

Reverts layout changes from 1.0 to fix block-layout-nesting bug.

There is a bug causing child blocks to be promoted up to ancestors when a nested layout/block is defined. It's not a common scenario, and probably hasn't been encountered in the wild yet since blocks were just introduced and haven't been documented yet. However, it's a bad bug, and would cause major problems if it surfaced.

The good news is that I know how to fix it. Bad news is that it will be time consuming and I need to make other changes before I get to that fix. Thus, in the meantime the best course of action is removing the blocks code.

1.0.0

Added

0.25.2

Fixed

0.25.1

Fixed

0.25.0

Added

0.24.3

Fixed

0.24.0

0.23.0

0.22.2

0.22.0

There should be no breaking changes in this release. If you experience a regression, please create an issue.

0.21.0

Breaking changes

Non-breaking

0.20.0

0.19.0

0.18.0

0.17.0

0.16.0

0.15.0

0.14.0

Although 99% of users won't be effected by the changes in this release, there were some potentially breaking changes.

0.13.0

0.12.0

0.11.0

0.10.7

0.10.6

0.10.0

0.9.5

0.9.4

0.9.0

0.8.0

0.7.0

0.5.1

About

Related projects

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Contributors

CommitsContributor
753jonschlinkert
105doowb
1chronzerg

Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Running tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test

Author

Jon Schlinkert

License

Copyright © 2017, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on July 27, 2017.