Giter VIP home page Giter VIP logo

templates's Introduction

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

  • 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 the instance for chaining.

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

  • fn {Function}: Plugin function. If the plugin returns a function it will be passed to the use method of each item created on the instance.
  • returns {Object}: Returns the instance for chaining.

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:

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

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

Params

  • opts {Object}: List options
  • returns {Object}: Returns the list instance for chaining.

Example

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

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

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 options
  • returns {Object}: Returns the collection instance for chaining.

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 options
  • returns {Object}: Returns the collection instance for chaining.

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

Params

  • app {Object}: Application instance
  • name {String}: Optionally pass the constructor name to use.
  • returns {undefined}

Example

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

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

Params

  • exts {String|Array}: String or array of file extensions.
  • fn {Function|Object}: or settings
  • 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');

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

Params

  • ext {String}: The engine to set.

Example

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

Get registered engine ext.

Params

  • ext {String}: The engine to get.

Example

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

Register a template helper.

Params

  • name {String}: Helper name
  • fn {Function}: Helper function.

Example

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

Register multiple template helpers.

Params

  • helpers {Object|Array}: Object, array of objects, or glob patterns.

Example

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

Register an async helper.

Params

  • name {String}: Helper name.
  • fn {Function}: Helper function

Example

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

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

Get a previously registered helper.

Params

  • name {String}: Helper name
  • returns {Function}: Returns the registered helper function.

Example

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

Get a previously registered async helper.

Params

  • name {String}: Helper name
  • returns {Function}: Returns the registered helper function.

Example

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

Return true if sync helper name is registered.

Params

  • name {String}: sync helper name
  • returns {Boolean}: Returns true if the sync helper is registered

Example

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

Return true if async helper name is registered.

Params

  • name {String}: Async helper name
  • returns {Boolean}: Returns true if the async helper is registered

Example

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

Register a namespaced helper group.

Params

  • helpers {Object|Array}: Object, array of objects, or glob patterns.

Example

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

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

Built-in helpers


View

API for the View class.

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

Params

  • view {Object}

Example

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

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

Synchronously render templates in view.content.

Params

  • locals {Object}: Optionally pass locals to the engine.
  • returns {Object} View: instance, for chaining.

Example

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

Asynchronously render templates in view.content.

Params

  • locals {Object}: Context to use for rendering templates.

Example

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

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

  • locals {Object}: Optionally pass a locals object to merge onto the context.
  • returns {Object}: Returns the context object.

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

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

  • type {String}: (renderable, partial, layout)

Example

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

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

Params

  • locals {Object}
  • returns {Object}

Example

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

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

Item

API for the Item class.

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

Params

  • item {Object}

Example

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

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'

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'

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

Views

API for the Views class.

Create an instance of Views with the given options.

Params

  • options {Object}

Example

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

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

Params

  • key {String|Object}: View key or object
  • value {Object}: If key is a string, value is the view object.
  • next {Function}: Optionally pass a callback function as the last argument to load the view asynchronously. This will also ensure that .onLoad middleware is executed asynchronously.
  • returns {Object}: returns the view instance.

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

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 object
  • value {Object}: If key is a string, value is the view object.
  • returns {Object}: returns the view instance.

Example

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

Get view name from collection.views.

Params

  • key {String}: Key of the view to get.
  • fn {Function}: Optionally pass a function to modify the key.
  • returns {Object}

Example

collection.getView('a.html');

Delete a view from collection views.

Params

  • key {String}
  • returns {Object}: Returns the instance for chaining

Example

views.deleteView('foo.html');

Load multiple views onto the collection.

Params

  • views {Object|Array}
  • returns {Object}: returns the collection object

Example

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

Load an array of views onto the collection.

Params

  • list {Array}
  • returns {Object}: returns the views instance

Example

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

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

  • returns {Object}: Returns an object of grouped views.

Example

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

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

Params

  • type {String}: (renderable, partial, layout)

Example

collection.isType('partial');

Alias for viewType

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

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 find
  • colleciton {String}: Optionally pass a collection name (e.g. pages)
  • returns {Object|undefined}: Returns the view if found, or undefined 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');

Get view key from the specified collection.

Params

  • collection {String}: Collection name, e.g. pages
  • key {String}: Template name
  • fn {Function}: Optionally pass a renameKey function
  • returns {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);
});

Get all views from a collection using the collection's singular or plural name.

Params

  • name {String}: The collection name, e.g. pages or page
  • returns {Object}

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.

Create an instance of Collection with the given options.

Params

  • options {Object}

Example

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

Add an item to the collection.

Params

  • key {String|Object}: Item name or object
  • val {Object}: Item object, when key is a string.
  • returns {Object}: returns the item instance.

Events

  • emits: item With the created item and collection instance as arguments.

Example

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

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

Params

  • key {String|Object}: Item name or object
  • val {Object}: Item object, when key is a string.
  • returns {Object}: returns the collection instance.

Events

  • emits: item With the created item and collection instance as arguments.

Example

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

Get an item from collection.items.

Params

  • key {String}: Key of the item to get.
  • returns {Object}

Example

collection.getItem('a.html');

Remove an item from collection.items.

Params

  • key {String}
  • returns {Object}: Returns the instance for chaining

Example

items.deleteItem('abc');

Load multiple items onto the collection.

Params

  • items {Object|Array}
  • returns {Object}: returns the instance for chaining

Example

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

Load an array of items onto the collection.

Params

  • items {Array}: or an instance of List
  • fn {Function}: Optional sync callback function that is called on each item.
  • returns {Object}: returns the Collection instance for chaining

Example

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

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

List

API for the List class.

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

  • options {Object}

Example

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

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

Params

  • key {String|Object}: Item key or object
  • value {Object}: If key is a string, value is the item object.
  • returns {Object}: returns the item instance.

Example

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

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

Params

  • key {String}
  • value {Object}
  • returns {Object}: Returns the instance of List to support chaining.

Example

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

Load multiple items onto the collection.

Params

  • items {Object|Array}
  • returns {Object}: returns the instance for chaining

Example

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

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

Params

  • items {Array}: or an instance of List
  • fn {Function}: Optional sync callback function that is called on each item.
  • returns {Object}: returns the List instance for chaining

Example

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

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

Params

  • key {String}
  • returns {Object}

Example

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

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

Params

  • key {String}
  • returns {Object}

Example

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

Get a specific item from the list by key.

Params

  • key {String}: The item name/key.
  • returns {Object}

Example

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

Proxy for getItem

Params

  • key {String}: Pass the key of the item to get.
  • returns {Object}

Example

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

Remove an item from the list.

Params

  • key {Object|String}: Pass an item instance (object) or item.key (string).

Example

list.deleteItem('a.html');

Remove one or more items from the list.

Params

  • items {Object|String|Array}: List of items to remove.

Example

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

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

Params

  • item {Object}
  • returns {Object}: Instance of item for chaining

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

  • returns {Object}: Returns a filtered array of items.

Example

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

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 new List instance with sorted items.

Example

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

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

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

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

Group

API for the Group class.

Create an instance of Group with the given options.

Params

  • options {Object}

Example

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

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 find
  • colleciton {String}: Optionally pass a collection name (e.g. pages)
  • returns {Object|undefined}: Returns the view if found, or undefined 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');

Get view key from the specified collection.

Params

  • collection {String}: Collection name, e.g. pages
  • key {String}: Template name
  • fn {Function}: Optionally pass a renameKey function
  • returns {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);
});

Get all views from a collection using the collection's singular or plural name.

Params

  • name {String}: The collection name, e.g. pages or page
  • returns {Object}

Example

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

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

Compile content with the given locals.

Params

  • view {Object|String}: View object.
  • locals {Object}
  • isAsync {Boolean}: Load async helpers
  • returns {Object}: View object with compiled view.fn property.

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

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

  • view {Object|String}: View object.
  • locals {Object}
  • isAsync {Boolean}: Pass true to load helpers as async (mostly used internally)
  • callback {Function}: function that exposes err and the view object with compiled view.fn property

Example

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

Render a view with the given locals and callback.

Params

  • view {Object|String}: Instance of View
  • 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
});

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 of Templates for chaining.

Example

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

Build the context for the given view and locals.

Params

  • view {Object}: The view being rendered
  • locals {Object}
  • returns {Object}: The object to be passed to engines/views as context.

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

Params

  • context {Object}
  • key {String}

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 of viewTypes to include on options.viewTypes
  • returns {Object}: Merged partials

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 of viewTypes to include on options.viewTypes
  • callback {Function}: Function that exposes err and partials parameters

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 a middleware method for file.

Params

  • method {String}: Name of the router method to handle. See router methods
  • file {Object}: View object
  • callback {Function}: Callback function
  • returns {undefined}

Example

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

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

Params

  • method {Object}: The name of the handler method to call.
  • file {Object}
  • returns {undefined}

Example

app.handleOnce('onLoad', file, callback);

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}: Returns the instance for chaining.

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

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

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

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

Params

  • method {String}: Name of the handler method to define.
  • returns {Object}: Returns the instance for chaining

Example

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

Add one or more router handler methods to the instance.

Params

  • methods {Array|String}: One or more method names to define.
  • returns {Object}: Returns the instance for chaining

Example

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

Example

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

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

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

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

Params

  • val {Object}: The value to test.
  • returns {Boolean}

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_:

  • added: for new features
  • changed: for changes in existing functionality
  • deprecated: for once-stable features removed in upcoming releases
  • removed: for deprecated features removed in this release
  • fixed: for any bug fixes

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.

Added

  • Templates now uses dry for handling layouts
  • Advanced template-inheritance features, like extends and blocks! See dry documentation for details.

Fixed

  • Correctly handles arguments for the built-in singular helper when used with Handlebars.

Fixed

  • Ensures the template rendering engine's context is preserved.

Added

  • Views can now be created asynchronously by passing a callback as the last argument to .addView (or the method created by .create, e.g. .page)

Fixed

  • Ensures the view object has engineStack and localsStack properties
  • Bumps base-data which removed renameKey option used when loading data. Use the namespace option instead.
  • fixes List bug that was caused collection helpers to explode

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

  • Externalizes a few core plugins to: base-helpers, base-routes, and [base-engine][]. The goal is to allow you to use only the plugins you need in your builds.
  • Improvements to lookup functions: app.getView() and app.find()
  • Bumps base to take advantages of code optimizations.

Breaking changes

  • The queue property has been removed, as well as related code for loading views using events. This behavior can easily be added using plugins or existing emitters.

Non-breaking

  • The View and Item class have been externalized to modules vinyl-item and vinyl-view so they can be used in other libraries.
  • Context: In general, context should be merged so that the most specific context wins over less specific. This fixes one case where locals was winning over front-matter
  • Helpers: Exposes .ctx() method on helper context, to simplify merging context in non-built-in helpers
  • Engines: Fixes bug that was using default engine on options instead of engine that matches view file extension.
  • Removed debug methods and related code
  • Improve layout handling with respect to template types (partial, renderable and layout)
  • Update dependencies
  • removes .removeItem method that was deprecated in v0.10.7 from List
  • .handleView is deprecated in favor of .handleOnce and will be removed in a future version. Start using .handleOnce now.
  • adds a static Templates.setup() method for initializing any setup code that should have access to the instance before any other use code is run.
  • upgrade to base-data v0.4.0, which adds app.option.set, app.option.get and app.option.merge

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

  • The render and compile methods were streamlined, making it clear that .mergePartials should not have been renamed to mergePartialsSync. So that change was reverted.
  • Helper context: Exposes a this.helper object to the context in helpers, which has the helper name and options that were set specifically for that helper
  • Helper context: Exposes a this.view object to the context in helpers, which is the current view being rendered. This was (and still is) always expose on this.context.view, but it makes sense to add this to the root of the context as a convenience. We will deprecate this.context.view in a future version.
  • Helper context: .get, .set and .merge methods on this.options, this.context and the this object in helpers.
  • All template handling is async by default. Instead of adding .compileSync, we felt that it made more sense to add .compileAsync, since .compile is a public method and most users will expect it to be sync, and .compile methods with most engines are typically sync. In other words, .compileAsync probably won't be seen by most users, but we wanted to explain the decision to go against node.js naming conventions.
  • Improved layout detection and handling
  • Default engine can now be defined on app or a collection using using app.option('engine'), views.option('engine')
  • Default layout can now defined using app.option('layout'), views.option('layout'). No changes have been made to view.layout, it should work as before. Resolves issue/#818
  • Improves logic for finding a layout, this should make layouts easier to define and find going forward.
  • The built-in view helper has been refactored completely. The helper is now async and renders the view before returning its content.
  • Adds isApp, isViews, isCollection, isList, isView, isGroup, and isItem static methods. All return true when the given value is an instance of the respective class.
  • Adds deleteItem method to List and Collection, and deleteView method to Views.
  • Last, the static _.proto property which is only exposed for unit tests was renamed to _.plugin.
  • Force-update base to v0.6.4 to take advantage of isRegistered feature.
  • Re-introduces fs logic to getView, now that the method has been refactored to be faster.
  • getView method no longer automatically reads views from the file system. This was undocumented before and, but it's a breaking change nonetheless. The removed functionality can easily be done in a plugin.
  • Fixes error messages when no engine is found for a view, and the view does not have a file extension.
  • Fixes a lookup bug in render and compile that was returning the first view that matched the given name from any collection. So if a partial and a page shared the same name, if the partial was matched first it was returned. Now the renderable view is rendered (e.g. page)
  • breaking change: changes parameters on app.context method. It now only accepts two arguments, view and locals, since ctx (the parameter that was removed) was technically being merged in twice.
  • Exposes isType method on view. Shouldn't be any breaking changes.
  • breaking change: renamed .error method to .formatError
  • adds mergeContext option
  • collection name is now emitted with view and item as the second argument
  • adds isType method for checking the viewType on a collection
  • also now emits an event with the collection name when a view is created
  • fixes bug where default layout was automatically applied to partials, causing an infinite loop in rare cases.

About

Related projects

  • assemble: Get the rocks out of your socks! Assemble makes you fast at creating web projectsโ€ฆ more | homepage
  • en-route: Routing for static site generators, build systems and task runners, heavily based on express.js routesโ€ฆ more | homepage
  • engine: Template engine based on Lo-Dash template, but adds features like the ability to register helpersโ€ฆ more | homepage
  • layouts: Wraps templates with layouts. Layouts can use other layouts and be nested to any depthโ€ฆ more | homepage
  • verb: Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is usedโ€ฆ more | homepage

Contributing

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

Contributors

Commits Contributor
753 jonschlinkert
105 doowb
1 chronzerg

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.

templates's People

Contributors

doowb avatar janderland avatar jonschlinkert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

templates's Issues

new view type: grid

@doowb and I had an interesting conversation a couple of days ago, as a result we're considering adding a fourth view type: grid, for handling grid systems.

(This is only a partially-formed idea. it's really interesting but is not yet "planned". Feedback welcome)

Synopsis

Whereas "view collections" are used for organizing and caching views, "view types" determine how the individual views in a collection will be handled during the render cycle. For example, views with the partial view type will be merged onto the context before being passed to the template engine for rendering, but views with the layout and renderable types will not.

View types

This library currently supports three view types: partial, renderable and layout. Passed on the viewType option when a collection is created, collections may have one or more view types, defaulting to renderable if no other types are defined.

  • partial: allows "partial views" to be injected into other views. useful for components, document fragments, or other snippets of reusable code or content.
  • layout: allows views to "wrap" other views (of any type, including other layouts or partials) with common code or content.
  • renderable: views that have a one-to-one relationship with rendered files that will eventually be visible to a user or visitor to a website. For example: pages or blog posts.

Proposed

The grid view type would combine concepts from the partial and layout types to allow users to pre-define complex page layout systems, whilst also keeping a separation of concerns between structure and content.

In practice, this means that grids themselves would be defined using a declarative configuration, the markup (rows and columns) of the grid would be entirely composed of user-defined views (templates), and the content that will eventually populate the individual "cells" of the grid can also be defined using a declarative configuration - allowing them to be modified on-the-fly during the build cycle (e.g. just as you can easily change the layout of a view using middleware, you could also customize the cells of a grid on a page-by-page, or collection-by-collection, or task-by-task basis).

The concept

This is totally pseudo-code, but hopefully you will get the idea and be able to give feedback.

Grids will be created like any other views.

app.create('foo', {viewType: 'grid'});

Once created, you would add grid views with app.foo() (like other custom collections). We would add support for two special properties unique to grids (we're open to suggestions on the property names):

  • schema: an object, for defining the actual grid system using columns, rows, and even other (nested) grids.
  • structure: an object that provides a semantic "mapping" between the grid-schema-object, and css-based grid "positions" that can be specified by other views (in other words, this would allow you to add a partial to the "banner" position on a grid, instead of row2.col1-col4 or whatever).
app.foo('magazine', {
  // main content here, along with a "grid" tag defining where the actual grid will be injected
  content: '<div>{% grid %}</div>',
  // grids can also use layouts, like any other view type
  layout: 'main',
  // rows and columns in the schema would define the "grid positions", as well as
  // the context for those individual "cells"
  schema: {
    row1: {
      // like layouts, the templates in "cells" would be resolved before injecting content
      content: '{% row %}',
      col1: {
        content: '{% col %}',
      }
    },
    row2: {
      col1: {
        content: '{% col %}',
      }
    },
    row3: {
      // nested grid
      grid: 'baz',
    }
  },
  structure: {
    nav: 'row1.col1',
    banner: 'row2.col1',
    main: 'row3.grid.row2.co2'
  }
});

Then, renderable views (like pages, posts etc) can specify a grid to use, along with with content to populate the cells. For example:

app.page('whatever', {
  content: 'this is some content...', 
  layout: 'default', 
  grid: {
    name: 'magazine',
    structure: {
      nav: {
        data: {span: 12},
        content: '<div class="nav">...</div>'
      },
      banner: {
        data: {span: 12},
        content: '<div class="banner">...</div>'
      },
      main: {
        data: {span: 6}
        content: 'some content or partials or whatever for the `main` cell on the `magazine` grid'
      }
    }
  }
});

tests

Tests were temporarily moved to base-test-suite to prevent creation of duplicate tests while we're updating all of the tests in the assemble, verb, update, generate and base libs.

async helpers (refactor, externalize, and improve!!!)

@jonschlinkert and I have talked about this and I've been looking through the current modules that have touch points to async helpers and trying some things out to try to improve the experience with some of the use cases that we've come across.

I think that the following steps can be taken to refactor and externalize some of the current pieces, while creating a couple new pieces for so cases:

  • refactor async-helpers

  • remove async-helpers from engine-cache

    • the only real touch points in engine-cache are adding helpers to the asyncHelpers instance when compiling, and resolving async helper ids after the string has been rendered
    • moving this out of engine-cache makes way for the next step
  • base-async-helpers module that adds the async-helpers functionality to base applications

    • move asyncHelper, asyncHelpers, getAsyncHelper, and hasAsyncHelper methods from base-helpers to `base-async-helpers
    • wrap engine-cache methods to inject the async-helpers functionality into .compile and .render (this can be more configurable and only enabled for specific engines)
  • Make built-in singular and plural helpers "smarter" to know if they're being used as async or sync helpers. Either split them out into a module or just check for the callback.

  • base-handlebars-async-helpers module to add necessary helpers and batch methods in Handlebars to allow using async-helpers with built in Handlebars partial syntax.

    • I've done this in an example and tried to implement it directly in engine-handlebars, but engine-handlebars is not able to get a reference to the asyncHelpers instance created by engine-cache.
    • I think splitting out the other pieces and adding this functionality as a plugin will let users choose when they're going to use async-helpers and if they'r using Handlebars, they can also include this module to fix some specific use cases.
    • Since we include engine-handlebars in assemble by default, we can include this also (or have an option to enable async-helpers which would then include base-async-helpers and base-handlebars-async-helpers)
  • optional base-engine-async-helpers module that will do something with engine-base to get async-helpers to work with regular javascript conditional statements (I don't know exactly how to do this yet, but we've thrown around a few ideas)

I'll be working on these changes over the next few days. Feedback is welcome and encouraged!

Rendering issue: a param from a previous render call gets injected

I have a basic setup: a layout and 2 views built on top of the layout. When I render the first view everything is OK, but when I render second view unless helper behaves in a weird way: it uses context param value of title from a previous call to render.

'use strict';

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

/**
 * Defin the engine to use
 */

app.engine('txt', require('engine-handlebars'));
app.option('engine', 'txt');

/**
 * Create view collections
 */

app.create('pages');
app.create('layouts', {viewType: 'layout'});
app.create('headings', {viewType: 'partial'});

/**
 * Add some views
 */

// layout
app.layout('base', {
  data: {},
  content: '<div>{{#unless title}}{{ title }}{{/unless}}<span>{% body %}</span>{{ title }}</div>',
});
app.option('layout', 'base');

// pages
app.page('one', {
  data: {title: 'title-A'},
  content: 'ONE',
});
app.page('two', {
  data: {},
  content: 'TWO',
});

/**
 * Render views
 */

app.render('one', {}, function(err, res) {
  if (err) return console.log(err.stack);
  console.log(res.content);
});
app.render('two', {}, function(err, res) {
  if (err) return console.log(err.stack);
  console.log(res.content);
});

Expected output:

<div><span>ONE</span>title-A</div>
<div><span>TWO</span></div>

Actual output:

<div><span>ONE</span>title-A</div>
<div>title-A<span>TWO</span></div>

Removed `view` property from page context

@doowb @jonschlinkert
I have some template tags in Nunjucks that rely data from the view property such as path and key. It looks like with templates 0.14.6 this may have potentially been removed. Any chance to get this back or should I deal with it in some middleware?

templates 0.13.7 => assemble-core 0.13.0

{ 
  ext: '.html',
  engineName: undefined,
  settings: {},
  view: <File "index.html" <Buffer 7b 25 20 65 78 74 65 6e 64 73 20 6c 61 79 6f 75 74 73 28 27 68 6f 6d 65 27 29 20 25 7d 0a 0a 7b 25 20 64 65 62 75 67 20 25 7d 0a 7b 25 20 62 6c 6f 63 ... >>,
  async: true,
  helpers:
   { view: [Function: wrapped],
     page: [Function: wrapped],
     pages: [Function: wrapped] 
   } 
}

templates 0.14.6 => assemble-core 0.13.2

{ ext: '.html',
  async: true,
  helpers:
   { view: [Function: wrapped],
     page: [Function: wrapped],
     pages: [Function: wrapped] 
   },
  engineName: undefined
}

Setup

https://github.com/dtothefp/build-boiler/blob/master/packages/boiler-addon-assemble-nunjucks/src/index.js#L11

  const ext = '.html';
  const nunj = nunjucks.configure({
    watch: false,
    noCache: true
  });

  app.engine(ext, consolidate.nunjucks);

https://github.com/dtothefp/build-boiler/blob/master/packages/boiler-addon-assemble-nunjucks/src/tags/get-asset.js#L86

//tempalte tag
export default class GetAsset {
  constructor(app) {
    this.app = app;
    this.tags = ['get_asset'];
  }

  parse(parser, nodes, lexer) {
    const tok = parser.nextToken();
    const args = parser.parseSignature(null, true);

    if (args.children.length === 0) {
      args.addChild(new nodes.Literal(0, 0, ''));
    }

    parser.advanceAfterBlockEnd(tok.value);
    return new nodes.CallExtension(this, 'run', args);
  }
  run(context, args) {
    const {ctx} = context;
    const {
      assets = {}, //from app.data => assets = {'some/page/path': '/some/src.js'}
      environment,
      view
    } = ctx;  //ctx is page context
    const {isDev} = environment;
    const {path: viewPath} = view;  //breaks here because there is no `view.path`

    return new nunjucks.runtime.SafeString(`<script src="${assets[viewPath]}"></script>`);
  }
}

https://github.com/dtothefp/build-boiler/blob/master/src/templates/layouts/default.html#L24

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

  {% get_asset %}
</body>
</html>

TypeError: this.debug.helpers is not a function

Using latest dev branch of verb, so templates is latest v0.14.5 (i checked it).

[charlike@voltaire bind-context]$ verb
/usr/local/lib/node_modules/verb/node_modules/templates/lib/plugins/helpers.js:79
    this.debug.helpers('getting async helper "%s"', name);
               ^

TypeError: this.debug.helpers is not a function
    at Verb.<anonymous> (/usr/local/lib/node_modules/verb/node_modules/templates/lib/plugins/helpers.js:79:16)
    at Verb.<anonymous> (/usr/local/lib/node_modules/verb/node_modules/templates/lib/plugins/helpers.js:116:24)
    at Object.module.exports (/usr/local/lib/node_modules/verb/node_modules/templates/lib/helpers/singular.js:7:11)
    at Verb.Templates.create (/usr/local/lib/node_modules/verb/node_modules/templates/index.js:316:11)
    at Verb.initVerb (/usr/local/lib/node_modules/verb/index.js:61:10)
    at new Verb (/usr/local/lib/node_modules/verb/index.js:32:8)
    at Verb (/usr/local/lib/node_modules/verb/index.js:28:12)
    at Object.<anonymous> (/usr/local/lib/node_modules/verb/bin/verb.js:12:11)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

And actually I can't realize how debug comes into utils, it's unreal hahaha, absolute absurd.

edit: Let's start. ./lib/debug.js is called on the constructor on line 56. In this file lazy-loaded modules and all files from lib/utils/* are merged, okey.

Layouts not working as expected

After setting everything up setting the layout on the index.pug file to be _layout and rendering it. This is what the output is.

Note: Below are the files that I used.

Actual:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </body>
</html>
<ul>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ul>
<h1>Partial</h1>
Expected
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    <ul>
      <li>item</li>
      <li>item</li>
      <li>item</li>
      <li>item</li>
    </ul>
    <h1>Partial</h1>
  </body>
</html>

_layout.pug

doctype html
html
  head
    meta(charset="utf-8")
  body
    {% body %}

index.pug

p Lorem ipsum dolor sit amet, consectetur adipisicing elit.

ul
  li item
  li item
  li item
  li item

!= helpers.partial('_partial')

_partial.pug

h1 Partial

render helper

Add an async render helper that takes a view object and locals

view missing context method

when a view is created without a collection, it will not have a context method, which throws an error in render. We can just decorate the same methods that are used on collection-views onto view to avoid this

Cannot find module 'async'

Hi

We're using a module named "assemble" and this module uses this one. The modules are installed with a "--production" flag. When using the assemble module, the following error occurs:

Error: Cannot find module 'async'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:286:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/var/app/buildslave/jenkins/workspace/Team Awesom-O/APM/APM Frontend/APM Frontend - deploy DEV/node_modules/assemble/node_modules/assemble-core/node_modules/templates/lib/plugins/context.js:3:13)

It seems the context.js file uses the async-module, but according to the package.json, this should just be a devDependency. I believe that's where the problem is located.

If you need any more information, let me know.

Kind regards,
Yannick

Documentation: What is the difference between templates and template?

I'm a quite heavy user of assemble. Maybe there is no reason to change something in assemble, but the project seems to be sleeping for a while and for that reason I was looking for the next big thing in static site generation. I encountered templates and template and they appear to be very similar, not just their names.

Could you please provide some information which project to use, depending on the case?

And I'm asking myself how much value assemble provides compared to templates. Is it much more than a grunt-plugin calling template and selecting a template engine (handlebars)?

Where would templates be used? Typically "offline" site generation or delivering "online", embedded in something like express?

I apologize if the questions are dumb, maybe I'm not deep enough in that business and as a result not able to imagine what to do with the more low-level libraries you provide. BTW thanks for your great work!

`TypeError: this.run is not a function`

This issue popped up today, not sure what is happening

"version": "0.15.11"

/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/templates/lib/views.js:157
  if (view.use) this.run(view);
                     ^

TypeError: this.run is not a function
    at Views.setView (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/templates/lib/views.js:157:22)
    at DestroyableTransform._transform (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/assemble-fs/index.js:152:25)
    at DestroyableTransform.Transform._read (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:159:10)
    at DestroyableTransform.Transform._write (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:147:83)
    at doWrite (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:313:64)
    at writeOrBuffer (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:302:5)
    at DestroyableTransform.Writable.write (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:241:11)
    at DestroyableTransform.ondata (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:531:20)
    at emitOne (events.js:90:13)
    at DestroyableTransform.emit (events.js:182:7)
    at readableAddChunk (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:198:18)
    at DestroyableTransform.Readable.push (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:157:10)
    at DestroyableTransform.Transform.push (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:123:32)
    at afterTransform (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:79:51)
    at TransformState.afterTransform (/Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:58:12)
    at /Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/vinyl-fs/lib/src/getContents/bufferFile.js:18:5
    at /Users/davidfox-powell/dev/balloon/balloon/server/static/node_modules/graceful-fs/graceful-fs.js:78:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:404:3)

goals for refactor

  • faster
  • take advantage of es6 classes and inheritance
  • simplify logic for caching views (renameKey, etc)
  • built-in support for permalinks
  • built-in support for pagination

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.