Vash

"... the 60 billion double-dollar template-maker!" ~ The previous README, and no one else, ever.

Vash is a template engine that offers a swift flow between code and content using Razor Syntax 1 . This document is intended for users of Vash, and also serves as a reference for Vash's implementation of Razor Syntax.

  1. Features
  2. Quick Start
    1. node/express
    2. Browser - Vanilla
    3. Browser - RequireJS
  3. Syntax
    1. The Transition Character: @
    2. Expressions
    3. Advanced Expressions
    4. Explicit Expressions
    5. Code Blocks
    6. Keyword Blocks
    7. Comments
    8. HTML Escaping
    9. Explicit Markup
  4. Helpers
    1. Buffer API
    2. Compiled Helpers
    3. vash.helpers.raw
    4. vash.helpers.escape
    5. vash.helpers.tplcache
  5. Precompiling Templates
  6. Vash Runtime (Browser)
  7. Compile-time API
    1. vash.compile
    2. vash.compileHelper
    3. vash.compileBatch
  8. Runtime API
    1. vash.link
  9. vash.config.*
  10. vash(1)
    1. --helper
  11. Special Thanks

Features

Quick Start

These examples are extremely simple. Especially for use in the browser, something more complex, like precompiling templates, is recommended.

node/express

Check out vash-express-example for a full example of hooking up vash as a view engine for express 3. But it's basically as simple as:

var express = require('express');

var app = express();
app.set('view engine', 'vash');

Browser - Vanilla

<script type="text/javascript" src="vash.min.js"></script>

var tpl = vash.compile( document.querySelector('#my-tpl').innerHTML );
document.querySelector('#content').innerHTML = tpl();

Browser - RequireJS

Be sure to configure paths appropriately, but vash is AMD ready.

require(['vash'], function(vash){
    var tpl = vash.compile( document.querySelector('#my-tpl').innerHTML );
    document.querySelector('#content').innerHTML = tpl();
})

Syntax

For the following examples, assume a model is passed into the compiled function. If a model is explicitly defined, it will appear as:

// model = { what: 'hello!' }

The Transition Character: @

Vash uses the @ symbol to transition between code and markup. To escape and print a literal @, use a double @, like this: @@.

Expressions

The most basic usage of Vash is an implicit expression. Vash is smart enough to know what's valid JS and what's not, and can usually do what you want it to do. And expression is an @ followed by a valid JS identifier. This is then interpolated automatically.

input:

// model = { what: 'hello!' }
<p>@what</p>

output:

<p>hello!</p>

The model comment is just to show that the object passed into the compiled template contains a key that matches the expression.

To allow for the fastest render time possible, Vash by default requires the model to be addressed explicitly. This is to avoid using a with statment in the compiled template, which is approximately 25 times slower. The above example then becomes:

input:

<p>@model.what</p>

output:

<p>hello!</p>

As you can see, the output is exactly the same. The name used to reference the model is configurable via [vash.config.modelName](#config-modelName). Typical values are model and it.

Advanced Expressions

Vash typically knows when an expression ends, even when the expression is complex. For example:

input:

<p>@model.what().who[2]('are you sure')('yes, it\'s ok')( model.complex ? 'FULL POWER' : '' )</p>

This will work just fine, assuming you have a model that actually contains that complexity! I hope you don't, and if so, I feel bad.

Callbacks work as well:

input:

// model = ['a', 'b']
@model.forEach(function(item){
    <li>@item</li>
})

outputs:

<li>a</li><li>b</li>

Vash also knows the difference between JS dot notation and a period.

input:

// model = { description: 'living' }
<p>Plants are @model.description.</p>

output:

<p>Plants are living.</p>

And empty brackets, because they're not valid JS:

input:

// model = { formName: 'addresses' }
<input type="text" name="@model.formName[]" />

output:

<input type="text" name="addresses[]" />

Email addresses, to an extent, are fine as well. Vash makes a trade-off. It uses the following regex to validate an email address:

/^([a-zA-Z0-9.%]+@[a-zA-Z0-9.\-]+\.(?:ca|co\.uk|com|edu|net|org))\b/

Email addresses can actually contain many more valid characters, and are really hard to validate. Vash can handle a typical email address with ease:

input:

<a href="mailto:vash@planetgunsmoke.com">Email Me</a>

output:

<a href="mailto:vash@planetgunsmoke.com">Email Me</a>

If you have a complex email address that confuses Vash, then you should use an explicit expression instead.

Explicit Expressions

An explicit expression is simply an expression that, instead of being composed of @ and a valid JS identifier, is surrounded by parenthesis.

input:

<p>@(model.what)</p>

output:

<p>hello!</p>

Why would you ever need this? Perhaps you want to do something like:

input:

// model = { hasIceCream: true }
<p class="@( model.hasIceCream ? 'ice-cream' : '')">Ice Cream<p>

output:

<p class="ice-cream">Ice Cream<p>

You could even create an anonymous function.

input:

@(function(type){ return type + ' cream'; }('banana'))

output:

banana creme

As you can see, Vash does not require a model to be referenced, or even passed in.

Code Blocks

Sometimes, AGAINST ALL ODDS, a template may need some quick computation of values to avoid repeating yourself. Unlike expressions and explicit expressions, a code block does not directly output. To compare to PHP, expressions are like <?= $what ?>, while a code block is like <? $what = 'what' ?>.

A code block is simply @{ }.

input:

@{ var rideOn = 'shooting star'; }

output:

That's right, nothing! Here's a better example:

input:

@{
    var total = model.price + model.tax;
}

<p>Your total is: $@total</p>

output:

<p>Your total is: $2.70</p>

Anything is valid within a code block, such as function declarations or even something as complex as defining a prototype. You can also use markup within a code block, and it will behave as expected:

input:

@{ <p>This works!</p> }

output:

<p>This works!</p>

A code block just tells Vash, 'expect the next stuff to be code until otherwise'.

Keyword Blocks

Vash is aware of keywords, and will open a code block automatically for you.

input:

// model = { type: 'banana' }
@if(model.type){
    <p>I'm a @model.type!</p>
} else if(model.name){
    <p>My name is @model.name.</p>
} else {
    <p>I DON'T KNOW WHO OR WHAT I AM...</p>
}

output:

<p>I'm a banana!</p>

This also works for while, for, do, try/catch, with, switch, function, and other keywords.

You don't even need to worry about whitespace or newlines:

input:

// model = true
@switch(model){case 1:<p></p>break;case 2:<b></b>break;}

output:

<p></p>

Comments

Vash also supports comments that are not compiled into the template. These are delineated with @* and *@

input:

@* I am a comment that extends
over multiple lines *@
<p>BANANA!</p>

output:

<p>BANANA!</p>

HTML Escaping

By default, Vash escapes any HTML-like values before outputting them.

input:

// model = { what: '<img />' }
<p>@model.what</p>

output:

<p>&lt;img /&gt;</p>

If you are sure that you trust the content, and/or need to display HTML-like values, you can escape the HTML escaping via a call to Vash's helper system: html.raw.

input:

// model = { what: '<img />' }
<p>@html.raw(model.what)</p>

output:

<p><img /></p>

Explicit Markup

Sometimes you may wish to tell Vash that what you're typing is markup or content, as opposed to code. Take the following example:

input:

// model = ['a']
@model.forEach(function(item){
    item
})

output:

(empty string)

In this situation, you have two options. The first is the @: (at colon) escape. It tells Vash that until it sees a newline, treat the input as content, not code.

input:

// model = ['a']
@model.forEach(function(item){
    @: item
})

output:

a

The other option, in the event that more than one line is needed, is by using an imaginary HTML tag named <text>. When Vash sees this tag, it switches to content mode, and discards the tag. This means that the tag will never be output.

input:

// model = ['Indeed!']
@model.forEach(function(item){
    <text>
        This is some longer content that you
        apparently wanted on multiple lines,
        multiple times! @item
    </text>
})

output:

This is some longer content that you
apparently wanted on multiple lines,
multiple times! Indeed!

Helpers

Vash's primary point of expandability lies in its Helper API. When a template is rendering, there is a free variable avaiable. This variable is, by default, named html. This name can be changed with the vash.config.helpersName option. html is an instance of the prototype that is attached to vash.helpers. It's a bit confusing, but this is how it kind of works:

js var Helpers = function(){} vash.helpers = Helpers.prototype; vash.helpers.constructor = Helpers;

What this means is that any function that is attached to vash.helpers is available within a rendering template via html. For example:

// defined in a JS file or script tag somewhere
vash.helpers.echo = function(arg){ return arg; }

input:

<p>@html.echo('hello!')</p>

output:

<p>hello!</p>

Buffer API

Within a helper, this refers to the current Helpers instance. Every instance has a Buffer that has methods to help easily add, subtract, or mark content put there by the rendering template.

Adding to the buffer:

vash.helpers.imgfigure = function(path, caption){
    vash.helpers.imgfigure.figcount = vash.helpers.imgfigure.figcount || 0;
    var figcount = vash.helpers.imgfigure.figcount++;
    this.buffer.push('<figure id="fig-' + figcount + '">';
    this.buffer.push('<img src="' + path + '" alt="' + caption + '" />';
    this.buffer.push('<figcaption>Fig.' + figcount + ':' + caption + '</figcaption>';
    this.buffer.push('</figure>');
}

Here is a simple helper that converts text like "This is a holdup!" to "this-is-a-holdup":

vash.helpers.mdHref = function(text){
    return text
        .toLowerCase()
        .replace(/[^a-zA-Z0-9-_]+/g, '-')
        .replace(/^-+|\n|-+$/g, '');
}

Notice how it's just JavaScript. Within a template, it can be accessed via html.mdHref("This is a holdup!").

Compiled Helpers

A relatively new feature in Vash (added in 0.6), compiled helpers are a bit meta. They allow a developer to write a helper using vash syntax instead of the manual buffer API. The above buffer API example imgfigure could be rewritten:

vash.helpers.imgfigure = function(path, caption){
    vash.helpers.imgfigure.figcount = vash.helpers.imgfigure.figcount || 0;
    var figcount = vash.helpers.imgfigure.figcount;
    <figure id="fig-@(figcount++)">
        <img src="@path" alt="@caption" />
        <figcaption>Fig. @figcount: @caption</figcaption>
    </figure>
}

There are two ways to compile a helper. The first is using vash.compileHelper, the second is using vash(1)'s --helper option.

vash.helpers.raw

Available as html.raw within an executing template. By default, all content that passes from a model to a template is HTML encoded. In the event that the text is trusted (or is already encoded), wrap the call in this function. For an example, see HTML Escaping;

vash.helpers.escape

Available as html.escape within an executing template, this is the method Vash uses to HTML encode model values. It can also be used manually.

vash.helpers.tplcache

The tplcache is just that, a place to put a global index of templates. This is used primarily for the more "view engine" aspects that Vash provides, as well as a default location for [precompiled templates][vash1--target-namespace] using vash(1).

Precompiling Templates

To save both processing time (compiling templates is not trivial) as well as bandwidth (no need to send the whole compiler to the client), Vash supports precompilation of templates. Any template that Vash compiles is given a method called toClientString. This method returns a string that can either be evaled or sent to a remote client. For example:

<p>Hello</p>

Compiles to a function:

function anonymous(model,html,__vopts,vash) {
    var __vbuffer = html.buffer; 
    html.options = __vopts; 
    model = model || {}; 
    __vbuffer.push('<p></p>\n'); 
    (__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, html)); 
    return (__vopts && __vopts.asContext) 
        ? html 
        : html.toString(); 
}

If toClientString is called on that function, the following is returned:

vash.link( function anonymous(model,html,__vopts,vash) {
    var __vbuffer = html.buffer; 
    html.options = __vopts; 
    model = model || {}; 
    __vbuffer.push('<p></p>\n'); 
    (__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, html)); 
    return (__vopts && __vopts.asContext) 
        ? html 
        : html.toString(); 
}, {"simple":false,"modelName":"model","helpersName":"html"} )

This string could then be sent to the client (probably prefixed with something like TPLCACHE["name-of-template"] = ). vash(1) helps to automate this easily.

Vash Runtime (Browser)

The Vash runtime is a set of functions that every executing template expects to be available. The runtime is automatically packaged with full Vash builds. However, if only precompiled templates are sent to the browser, then the runtime must also be sent. The runtime includes all helpers and a few standard functions, such as HTML Escaping.

Compile-time API

vash.compile

vash.compile(str_template, opt_options)

At it's core, Vash has a compile function that accepts a string and options, and returns a function, otherwise known as a compiled template. That function, when called with a parameter (otherwise known as a model), will use that parameter to fill in the template. A model can be any value, including undefined, objects, arrays, strings, and booleans.

vash.compileHelper

vash.compileHelper(str_template, opt_options)

See Compiled Helpers for more detail.

vash.compileBatch

vash.compileBatch(str_template, opt_options)

This function can take a single string containing many named templates, and output an object containing the compiled versions of those templates. A "named template" is of the form (similar to a sourceURL):

//@batch = div
<div>@model</div>\n'

//@batch = a
<a>@model</a>'

This example contains two named templates, "div" and "a". If this example were passed as a single string to compileBatch:

var tpls = vash.compileBatch(theTplString);

One could be called:

tpls.div('yes!');
// returns: <div>yes!</div>

This is meant as a convenience function for developers. Putting each template in a separate file can get old, especially if a template is small. Instead, templates can be grouped together.

Aside from the newline following the "name" of the template, whitespace is ignored:

//@              batch = div
//@batch=div
//         @batch =div

Each is treated the same.

Runtime API

vash.link

vash.link(str_template_or_func, options)

This is primarily an internal function. It takes either a string function or function instance and "links" it by wrapping it in a closure that provides access to Vash's runtime functions. It also sets up things like toClientString and toString.

vash.lookup

vash.install

vash.uninstall

In the Browser

vash.config.*

vash(1)

Vash also includes a commandline tool that enables easy integration of templates into a unix toolchain. For example, to compile this documentation, the following command is used:

<README2.vash bin/vash --render --helpers <(bin/vash --helper <docs/helpers/*)

This directs README2.vash into bin/vash. bin/vash has been told to --render its input, and to use the given --helpers file (which is raw JS executed in the context of the rendering template). --helpers is a temporary named pipe created via bin/vash using the --helper option, which instructs vash(1) to assume the input (all files in docs/helpers/) should be compiled as helpers.

vash(1) has many options:

-h, --help                          output usage information
-t, --target-namespace <namespace>  Assign template to a <namespace>. Recommended is `vash.helpers.tplcache` for view engine compatibility
-p, --property-name [name]          Assign template to property named <name>. Defaults to filename, and requires --target-namespace.
-f, --file <file>                   Compile the template in <file>
-j, --json <json>                   Pass options to the Vash compiler. See docs for valid options.
-o, --out <path>                    Write template into <path> directory
-u, --uglify                        Uglify the template, safely
-a, --no-autolink                   Wrap each template in `vash.link`.
-r, --render [json]                 Render the template using <json> as the model
-s, --separator [separator]         Templates are auto-named by concatenating the file path with [separator]
--helper                            Assume the input is a to-be-compiled helper
--helpers <file>                    Execute these compiled helpers

Some of the options are explained in greater detail below.

--helper

This instructs vash(1) to call vash.compileHelper instead of vash.compile, and assumes the input is a template that is meant to be a compiled helper. To illustrate:

An empty helper:

$ echo 'vash.helpers.who = function(){}' | bin/vash --helper --json '{"debug":false}'

vash.link( function anonymous() {
var __vbuffer = this.buffer; 
var model = this.model; 
var html = this; 
{}
}, {"simple":false,"modelName":"model","helpersName":"html","args":[""],"asHelper":"who"} )

And without --helper, vash(1) just outputs an empty template:

$ echo 'vash.helpers.who = function(){}' | bin/vash --json '{"debug":false}'

vash.link( function anonymous(model,html,__vopts,vash) {
var __vbuffer = html.buffer; 
html.options = __vopts; 
model = model || {}; 
__vbuffer.push('vash.helpers.who = function(){}\n'); 
(__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, html)); 
return (__vopts && __vopts.asContext) 
  ? html 
  : html.toString(); 
}, {"simple":false,"modelName":"model","helpersName":"html"} )

Special Thanks

Extreme thanks goes to TJ Holowaychuck and his template engine Jade. It was the original inspiration for Vash's lexer and Vash's layout helpers, and has been a constant source of inspiration and motivation.

  • Razor syntax was developed at Microsoft, and typically refers to their Razor View Engine, which ships with ASP.NET MVC 3 and above. In this document, "Razor" will refer to the Razor View Engine, while "syntax" or "Vash syntax" refers to Vash's implementation. ↩