• Stars
    star
    3,476
  • Rank 12,232 (Top 0.3 %)
  • Language
    JavaScript
  • Created over 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Template engine consolidation library for node.js

Consolidate.js

Template engine consolidation library.

Installation

$ npm install consolidate

Supported Express versions

Supported template engines

Some package has the same key name, consolidate will load them according to the order number. By example for dust, consolidate will try to use in this order: dust, dustjs-helpers and dustjs-linkedin. If dust is installed, dustjs-linkedin will not be used by consolidate.

Name cons.* Package Name / Order Website / State
atpl npm install atpl -
bracket npm install bracket-template -
dot npm install dot (website)
dust npm install dust (1) (website) / (unmaintained)
See: dustjs-linkedin
dust npm install dustjs-helpers (2) or
npm install dustjs-linkedin (3)
(website)
eco npm install eco /!\ Security issue
ect npm install ect (website)
ejs npm install ejs (website)
hamlet npm install hamlet -
hamljs npm install hamljs -
haml-coffee npm install haml-coffee -
handlebars npm install handlebars (website)
hogan npm install hogan.js (website)
htmling npm install htmling -
jade npm install jade (website) / (renamed pug)
jazz npm install jazz -
jqtpl npm install jqtpl (deprecated)
just npm install just -
liquid npm install tinyliquid (website)
will never add any new features
liquor npm install liquor -
lodash npm install lodash (website)
marko npm install marko (website)
mote npm install mote (website)
mustache npm install mustache -
nunjucks npm install nunjucks (website)
plates npm install plates -
pug npm install pug (website) / (formerly jade)
qejs npm install qejs -
ractive npm install ractive -
razor npm install razor -
react npm install react -
slm npm install slm -
squirrelly npm install squirrelly (website)
swig npm install swig (1) (unmaintained)
See: swig-templates
swig npm install swig-templates (2) -
teacup npm install teacup -
templayed npm install templayed (website)
toffee npm install toffee -
twig npm install twig (wiki)
twing npm install twing (website)
underscore npm install underscore (website)
vash npm install vash -
velocityjs BETA (website)
walrus npm install walrus (website)
whiskers npm install whiskers -

NOTE: you must still install the engines you wish to use, add them to your package.json dependencies.

API

All templates supported by this library may be rendered using the signature (path[, locals], callback) as shown below, which happens to be the signature that Express supports so any of these engines may be used within Express.

NOTE: All this example code uses cons.swig for the swig template engine. Replace swig with whatever templating you are using. For example, use cons.hogan for hogan.js, cons.jade for jade, etc. console.log(cons) for the full list of identifiers.

var cons = require('consolidate');
cons.swig('views/page.html', { user: 'tobi' }, function(err, html){
  if (err) throw err;
  console.log(html);
});

Or without options / local variables:

var cons = require('consolidate');
cons.swig('views/page.html', function(err, html){
  if (err) throw err;
  console.log(html);
});

To dynamically pass the engine, simply use the subscript operator and a variable:

var cons = require('consolidate')
  , name = 'swig';

cons[name]('views/page.html', { user: 'tobi' }, function(err, html){
  if (err) throw err;
  console.log(html);
});

Promises

Additionally, all templates optionally return a promise if no callback function is provided. The promise represents the eventual result of the template function which will either resolve to a string, compiled from the template, or be rejected. Promises expose a then method which registers callbacks to receive the promise’s eventual value and a catch method which the reason why the promise could not be fulfilled. Promises allow more synchronous-like code structure and solve issues like race conditions.

var cons = require('consolidate');

cons.swig('views/page.html', { user: 'tobi' })
  .then(function (html) {
    console.log(html);
  })
  .catch(function (err) {
    throw err;
  });

Caching

To enable caching simply pass { cache: true }. Engines may use this option to cache things reading the file contents, compiled Functions etc. Engines which do not support this may simply ignore it. All engines that consolidate.js implements I/O for will cache the file contents, ideal for production environments. When using consolidate directly: cons.swig('views/page.html', { user: 'tobi', cache:true }, callback); Using supported Express versions: app.locals.cache = true or set NODE_ENV to 'production' and Express will do this for you.

Express example

var express = require('express')
  , cons = require('consolidate')
  , app = express();

// assign the swig engine to .html files
app.engine('html', cons.swig);

// set .html as the default extension
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

var users = [];
users.push({ name: 'tobi' });
users.push({ name: 'loki' });
users.push({ name: 'jane' });

app.get('/', function(req, res){
  res.render('index', {
    title: 'Consolidate.js'
  });
});

app.get('/users', function(req, res){
  res.render('users', {
    title: 'Users',
    users: users
  });
});

app.listen(3000);
console.log('Express server listening on port 3000');

Template Engine Instances

Template engines are exposed via the cons.requires object, but they are not instantiated until you've called the cons[engine].render() method. You can instantiate them manually beforehand if you want to add filters, globals, mixins, or other engine features.

var cons = require('consolidate'),
  nunjucks = require('nunjucks');

// add nunjucks to requires so filters can be
// added and the same instance will be used inside the render method
cons.requires.nunjucks = nunjucks.configure();

cons.requires.nunjucks.addFilter('foo', function () {
  return 'bar';
});

Notes

  • If you're using Nunjucks, please take a look at the exports.nunjucks.render function in lib.consolidate.js. You can pass your own engine/environment via options.nunjucksEnv, or if you want to support Express you can pass options.settings.views, or if you have another use case, pass options.nunjucks (see the code for more insight).
  • You can pass partials with options.partials
  • For using template inheritance with nunjucks, you can pass a loader with options.loader.
  • To use filters with tinyliquid, use options.filters and specify an array of properties, each of which is a named filter function. A filter function takes a string as a parameter and returns a modified version of it.
  • To use custom tags with tinyliquid, use options.customTags to specify an array of tag functions that follow the tinyliquid custom tag definition.
  • The default directory used with the include tag with tinyliquid is the current working directory. To override this, use options.includeDir.
  • React To render content into a html base template (eg. index.html of your React app), pass the path of the template with options.base.

Running tests

Install dev deps:

$ npm install -d

Run the tests:

$ make test

License

(The MIT License)

Copyright (c) 2011-2016 TJ Holowaychuk <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

commander.js

node.js command-line interfaces made easy
JavaScript
26,053
star
2

n

Node version management
Shell
18,395
star
3

git-extras

GIT utilities -- repo summary, repl, changelog population, author commit percentages and more
Shell
16,697
star
4

co

The ultimate generator based flow-control goodness for nodejs (supports thunks, promises, etc)
JavaScript
11,853
star
5

ejs

Embedded JavaScript templates for node
JavaScript
4,450
star
6

node-prune

Remove unnecessary files from node_modules (.md, .ts, ...)
Go
4,297
star
7

frontend-boilerplate

webpack-react-redux-babel-autoprefixer-hmr-postcss-css-modules-rucksack-boilerplate (unmaintained, I don't use it anymore)
JavaScript
2,939
star
8

connect-redis

Redis session store for Connect
TypeScript
2,775
star
9

should.js

BDD style assertions for node.js -- test framework agnostic
JavaScript
2,757
star
10

luna

luna programming language - a small, elegant VM implemented in C
C
2,446
star
11

dox

JavaScript documentation generator for node using markdown and jsdoc
JavaScript
2,155
star
12

mmake

Modern Make
Go
1,701
star
13

node-migrate

Abstract migration framework for node
JavaScript
1,522
star
14

terminal-table

Ruby ASCII Table Generator, simple and feature rich.
Ruby
1,504
star
15

axon

message-oriented socket library for node.js heavily inspired by zeromq
JavaScript
1,494
star
16

react-enroute

React router with a small footprint for modern browsers
JavaScript
1,491
star
17

commander

The complete solution for Ruby command-line executables
Ruby
1,090
star
18

mon

mon(1) - Simple single-process process monitoring program written in C
C
1,065
star
19

reds

light-weight, insanely simple full text search module for node.js - backed by Redis
JavaScript
891
star
20

node-thunkify

Turn a regular node function into one which returns a thunk
JavaScript
858
star
21

robo

Simple Go / YAML-based task runner for the team.
Go
781
star
22

react-click-outside

ClickOutside component for React.
JavaScript
775
star
23

gobinaries

Golang binaries compiled on-demand for your system
Go
770
star
24

node-blocked

Check if the event loop is blocked
JavaScript
722
star
25

node-ratelimiter

Abstract rate limiter for nodejs
JavaScript
715
star
26

staticgen

Static website generator that lets you use HTTP servers and frameworks you already know
Go
712
star
27

histo

beautiful charts in the terminal for static or streaming data
C
697
star
28

serve

Simple command-line file / directory server built with connect - supports stylus, jade, etc
JavaScript
563
star
29

styl

Flexible and fast modular CSS preprocessor built on top of Rework
JavaScript
525
star
30

pomo

Ruby Pomodoro app for the command-line (time / task management)
Ruby
524
star
31

go-spin

Terminal spinner package for Golang
Go
521
star
32

mdconf

Markdown driven configuration!
JavaScript
507
star
33

node-growl

growl unobtrusive notification system for nodejs
JavaScript
484
star
34

watch

watch(1) periodically executes the given command - useful for auto-testing, auto-building, auto-anything
C
458
star
35

node-querystring

querystring parser for node and the browser - supporting nesting (used by Express, Connect, etc)
JavaScript
452
star
36

node-delegates

Nodejs method and accessor delegation utility
JavaScript
418
star
37

haml.js

Faster Haml JavaScript implementation for nodejs
JavaScript
409
star
38

triage

Interactive command-line GitHub issue & notification triaging tool.
Go
399
star
39

log.js

super light-weight nodejs logging + streaming log reader
HTML
368
star
40

go-tea

Tea provides an Elm inspired functional framework for interactive command-line programs.
Go
364
star
41

punt

Elegant UDP messaging for nodejs
JavaScript
341
star
42

react-fatigue-dev

Module of modules for making modules
Makefile
312
star
43

php-selector

PHP DOM parser / queries with CSS selectors
PHP
299
star
44

node-gify

Convert videos to gifs using ffmpeg and gifsicle
JavaScript
296
star
45

palette

Node.js image color palette extraction with node-canvas
JavaScript
292
star
46

better-assert

c-style assert() for nodejs, reporting the expression string as the error message
JavaScript
285
star
47

js-yaml

CommonJS YAML Parser -- fast, elegant and tiny yaml parser for javascript
JavaScript
275
star
48

go-naturaldate

Natural date/time parsing for Go.
Go
272
star
49

lingo

Linguistics module for Node - inflection, transformation, i18n and more
JavaScript
271
star
50

react-batch

Batch component for performant frequent updates (flush on count or interval)
JavaScript
251
star
51

sponsors-api

GitHub Sponsor avatar listings in your Readme.md
Go
244
star
52

mad

mad(1) is a markdown manual page viewer
Shell
244
star
53

d3-heatmap

D3 heatmap
JavaScript
243
star
54

go-update

Go package for auto-updating system-specific binaries via GitHub releases.
Go
241
star
55

callsite

node.js access to v8's "raw" CallSites -- useful for custom traces, c-style assertions, getting the line number in execution etc
JavaScript
239
star
56

bm

CLI bookmarks -- dropbox persisted bookmarks in your terminal - view screenshots in your browser
Shell
227
star
57

term-canvas

javascript canvas api for your terminal!
JavaScript
226
star
58

go-termd

Package termd provides terminal markdown rendering, with code block syntax highlighting support.
Go
224
star
59

parse-curl.js

Parse curl commands, returning an object representing the request.
JavaScript
217
star
60

go-progress

Another Go progress bar
Go
216
star
61

es

Go DSL for Elasticsearch queries
Go
206
star
62

co-prompt

sane terminal user-input for node.js using thunks / generators
JavaScript
193
star
63

node-cookie-signature

cookie signing
JavaScript
175
star
64

co-views

Higher-level template rendering for node.js using generators
JavaScript
175
star
65

d3-bar

D3 bar chart
JavaScript
173
star
66

node-only

return whitelisted properties of an object
JavaScript
170
star
67

ngen

nodejs project generator
JavaScript
168
star
68

react-hooks

Fire off actions in stateless components.
JavaScript
167
star
69

letterbox

Go program to batch-process letter-boxing of photographs.
Go
164
star
70

go-search

Search Godoc.org via the command-line.
Go
159
star
71

co-monk

MongoDB generator goodness for node.js
JavaScript
155
star
72

eson

Extended (pluggable) JSON for node - great for configuration files and JSON transformations
JavaScript
150
star
73

growl

Ruby growlnotify 'bindings' (unobtrusive notification system)
Ruby
146
star
74

go

Go packages
Go
140
star
75

d3-series

D3 line series chart used for error reporting on Apex Ping
JavaScript
139
star
76

channel.js

Go-style channel implementation for JavaScript
JavaScript
135
star
77

node-amp

Abstract message protocol for nodejs
JavaScript
135
star
78

burl

better curl(1) through augmentation
Shell
134
star
79

jog

JSON document logging & filtering inspired by loggly for node.js
JavaScript
132
star
80

node-pwd

Hash and compare passwords with pbkdf2
JavaScript
131
star
81

nedis

Redis server implementation written with nodejs
JavaScript
130
star
82

d3-circle

D3 circle chart
JavaScript
130
star
83

d3-dot

D3 dot chart
JavaScript
129
star
84

node-term-list

Interactive terminal list for nodejs
JavaScript
126
star
85

node-comment-macros

JavaScript comment macros useful for injecting logging, tracing, debugging, or stats related code.
JavaScript
126
star
86

d3-line

D3 line chart
JavaScript
125
star
87

asset

little asset manager for lazy people (think bundler/homebrew/npm for assets). written with node
JavaScript
122
star
88

go-dropbox

Dropbox v2 client for Go.
Go
120
star
89

node-term-css

style terminal output using CSS
JavaScript
116
star
90

go-terminput

Package terminput provides terminal keyboard input for interactive command-line tools.
Go
114
star
91

vscode-snippets

Personal VSCode snippets for Go, JS, Elm, etc.
114
star
92

nshell

scriptable command-line shell written with node.js
JavaScript
109
star
93

node-actorify

Turn any node.js duplex stream into an actor
JavaScript
108
star
94

co-parallel

Execute thunks in parallel with concurrency support
JavaScript
108
star
95

node-monquery

mongodb query language for humans
JavaScript
106
star
96

co-fs

nodejs core fs module thunk wrappers for "co"
JavaScript
105
star
97

axon-rpc

Axon RPC client / server
JavaScript
103
star
98

s3.js

S3 uploads from the browser.
JavaScript
100
star
99

spa

Tiny Single Page Application server for Go with `spa` command-line tool.
Go
94
star
100

d3-tipy

D3 tooltip
JavaScript
94
star