Compstache
Compstache extends Mustache and adds support for component based architecture.
Example
var Compstache = require('compstache');
var cache = {
button: '<button>Click here</button>',
layout: '<html><body>Welcome to {{title}}. ' +
'{{>button}} <div>{{{$}}}</div> ' +
'<hr/> Copyright © 2016 </body></html>',
home: '{{#>layout}}This site is all about {{topic}}.{{/>layout}}'
};
var render = Compstache(cache);
var output = render('home', {
title: 'CRAP',
topic: 'Contrast, Repetition, Alignment, and Proximity'
});
console.log(output); // render the template
See the Mustache documentation for all the base capabilities.
Additions
Compstache adds the following to Mustache:
Components
A component is simply an "include" (in the Mustache sense). You can include anything in cache
.
For instance, {{>button}}
renders as the template string in cache['button']
.
Layout Components
A layout component is simply a "section" (in the Mustache sense) that matches a component name in cache
that has one or more slots marked by {{{$}}}
.
For instance, if cache['layout']
is start {{{$}}} finish
, then {{#>layout}}content{{/>layout}}
renders as the template string with the inner content being injected into the slot, that is, "start content finish".
Multi-slot Layout Components
A layout component can have more than one slot. You can pass the content for multiple slots by wrapping them in {{#_}}
and {{/_}}
markers.
Example: Express View Engine
You can use Compstache as the view engine for an Express server. The following example shows a configuration to render HTML templates in a views
directory.
var app = require('express')();
app.engine('html', require('compstache').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');