@{ // shortcuts var fn = html.mdFn.bind(html) ,toc = html.mdToc.bind(html) ,lvl1 = html.mdTocLvlX.bind(html, 1) ,lvl2 = html.mdTocLvlX.bind(html, 2) } 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][] @fn('razor-ms'). This document @fn('this-doc') is intended for users of Vash, and also serves as a reference for Vash's implementation of Razor Syntax. [Razor Syntax]: http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax [![Build Status](https://secure.travis-ci.org/kirbysayshi/vash.png?branch=master)](https://travis-ci.org/kirbysayshi/vash) [![NPM](https://nodei.co/npm/vash.png?downloads=true&stars=true)](https://nodei.co/npm/vash/) [![NPM](https://nodei.co/npm-dl/vash.png)](https://nodei.co/npm/vash/) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/kirbysayshi/vash/trend.png)](https://bitdeli.com/free "Bitdeli Badge") @toc() Features @lvl1() ================ * Mix code and content without ugly delineators, like ``, `<%`, or `{{`. * No new language to learn: Vash is just HTML-aware JavaScript. * Great with markup, but can be used with nearly any other language as well (even Markdown!). * Helpers API allows for extensibility and meta programming. * Works in the browser or in node. * Comes with a Jade-inspired layout engine (block, include, extend, append/prepend), which even works in the browser. Syntax Example @lvl1() ======================
How are you @@model.name? Today is a sunny day on the planet Gunsmoke.
I am a @@model.t!
'); var out = tpl({ t: 'template' }); //I am a template!
express @lvl2() -------------------- 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'); More information is also available in the [Layout Helpers][] sections. [vash-express-example]: https://github.com/kirbysayshi/vash-express-example Browser - Vanilla @lvl2() ------------------------- var tpl = vash.compile( 'I am a @@model.t!
' ); document.querySelector('#content').innerHTML = tpl({ t: 'template' }); Browser - Browserify et al @lvl2() ---------------------------------- Just `require` Vash, and compile. If you want something fancier, try [vashify](https://www.npmjs.com/package/vashify)! Browser - RequireJS @lvl2() --------------------------- RequireJS support has been recently dropped. However Vash does support CJS environments, so as long as you configure RequireJS to consume Vash as a CJS project (including `node_modules` resolution), everything should work. Playground @lvl1() ================== Vash now has [a playground][] of sorts at [CodePen.io][]. It uses the current version of `vash.js` from the `build` folder. Fork it to test your own template ideas! [a playground]: http://codepen.io/kirbysayshi/full/IjrFw [CodePen.io]: http://codepen.io Syntax @lvl1() ============== 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: @@ @lvl2() ------------------------------------ Vash uses the `@@` symbol to transition between code and markup. To escape and print a literal `@@`, use a double `@@`, like this: `@@@@`. Expressions @lvl2() ------------------- 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. An expression is an @@ followed by a valid JS identifier. This is then interpolated automatically. input: // model = { what: 'hello!' }@@what
output:hello!
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:@@model.what
output:hello!
As you can see, the output is exactly the same. The name used to reference the model is configurable via [vash.config.modelName][]. Typical values are `model` and `it`. Advanced Expressions @lvl2() ---------------------------- Vash typically knows when an expression ends, even when the expression is complex. For example: input:@@model.what().who[2]('are you sure')('yes, it\'s ok')( model.complex ? 'FULL POWER' : '' )
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){Plants are @@model.description.
output:Plants are living.
And empty brackets, because they're not valid JS: input: // model = { formName: 'addresses' } output: 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: Email Me output: Email Me If you have a complex email address that confuses Vash, then you should use an [explicit expression](#explicit-expressions) instead. [really hard to validate]: http://www.regular-expressions.info/email.html Explicit Expressions @lvl2() ---------------------------- An explicit expression is simply an expression that, instead of being composed of `@@` and a valid JS identifier, is surrounded by parenthesis. input:@@(model.what)
output:hello!
Why would you ever need this? Perhaps you want to do something like: input: // model = { hasIceCream: true }Ice Cream
output:
Ice Cream
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 @lvl2() ------------------- 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; }
Your total is: $@@total
output:Your total is: $2.70
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: @@{This works!
} output:This works!
A code block just tells Vash, "expect the next stuff to be code until otherwise". Keyword Blocks @lvl2() ---------------------- Vash is aware of keywords, and will open a code block automatically for you. input: // model = { type: 'banana' } @@if(model.type){I'm a @@model.type!
} else if(model.name){My name is @@model.name.
} else {I DON'T KNOW WHO OR WHAT I AM...
} output:I'm a banana!
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 = 1 @@switch(model){case 1:break;case 2:break;} output: Comments @lvl2() ---------------- 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 *@@BANANA!
output:BANANA!
HTML Escaping @lvl2() --------------------- By default, Vash escapes any HTML-like values before outputting them. input: // model = { what: '' }@@model.what
output:<img />
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: '' }@@html.raw(model.what)
output: This behavior can be disabled using [vash.config.htmlEscape][]. Explicit Markup @lvl2() ----------------------- 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 `@html.raw('My tpl
', { debug: true }); vash.config.useWith @lvl2() --------------------------- Default: false If `useWith` is set to `true`, then Vash will wrap a `with` block around the contents of the compiled function. // vash.config.useWith == true'); html.vl = 1, html.vc = 3; __vbuffer.push('
'); html.vl = 1, html.vc = 7; __vbuffer.push('\n'); (__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, html)); return (__vopts && __vopts.asContext) ? html : html.toString(); } catch( e ){ html.reportError( e, html.vl, html.vc, "!@html.raw('L')@html.raw('B')!" ); } } And that same template with `debug` set to `false`: function anonymous(model,html,__vopts,vash) { var __vbuffer = html.buffer; html.options = __vopts; model = model || {}; __vbuffer.push('\n'); (__vopts && __vopts.onRenderEnd && __vopts.onRenderEnd(null, html)); return (__vopts && __vopts.asContext) ? html : html.toString(); } As you can see, the difference, especially in code size and instruction size is significant. For production apps, templates should be precompiled with `debug` as `false`. vash.config.debugParser @lvl2() ------------------------------- Default: false Vash's parser will output useful debugging infomation if `debugParser` is `true`: * Tokens and what mode they were processed as * A textual representation of the fully parsed AST vash.config.debugCompiler @lvl2() --------------------------------- Default: false Vash's compiler will output useful debugging information if `debugCompiler` is `true`: * The text content of the template function before it is passed into [vash.link][] for actual evaluation * The options passed into the compiler. This is useful for debugging [vash.compileBatch][] and [vash.compileHelper][]. vash.config.simple @lvl2() -------------------------- Default: false If `true`, the template is compiled in "fast path" mode. This disables several advanced features for the sake of speed: * [onRenderEnd][] callbacks are completely ignored. * The [Helper System][] instance normally available within a running template as `html` is no longer an instance of `vash.helpers.constructor`, and thus the entire buffer API and helpers are missing. Instead it is a plain object with the following properties: * `buffer`: a plain array * `escape`: [vash.helpers.escape][] * `raw`: [vash.helpers.raw][] * The [asContext][] runtime option is completely ignored. * [vash.config.htmlEscape][], [vash.config.useWith][], and [vash.config.debug][] still behave as expected. While standard Vash templates are definitely not slow, using `true` for this option decreases render time by 15% - 25% depending on the size of the template. [vash-benchgraph](https://github.com/kirbysayshi/vash-benchgraph) can be used to show the speed increase: node benches.js --tinclude 004.vash,007.vash --vinclude '0.6.2-2482' --chart vashv,ops vash.config.favorText @lvl2() ----------------------------- Default: false When Vash encounters text that directly follows an opening brace of a block, it assumes that unless it encounters an HTML tag, the text is JS code. For example: @@it.forEach(function(a){ var b = a; // vash assumes this line is code }) When `favorText` is set to `true`, Vash will instead assume that most things are content (not code) unless it's very explicit. @@it.forEach(function(a){ var b = a; // vash.config.favorText assumes this line is content }) This option is __EXPERIMENTAL__, and should be treated as such. It allows Vash to be used in a context like [Markdown](http://daringfireball.net/projects/markdown/syntax), where HTML tags, which typically help Vash tell the difference between code and content, are rare. Template Options @lvl1() ======================== These options concern rendering a template, after it has already been compiled. For options related to compiling templates, see [Configuration][]. The compiled templates themselves have three signatures. tpl(model) -> string The most basic form accepts a single argument, `model`, that can be any value: Number, Boolean, Object, Array, undefined, null, etc. It returns the rendered template as a string. tpl(model, function(){}) -> string The second form accepts a function callback as its second parameter, which is called [onRenderEnd][] (see below). tpl(model, options) -> string The third form allows for options in addition to [onRenderEnd][]. There are two options that can affect a template while rendering: asContext @lvl2() ----------------- tpl(model, { asContext: true }) -> vash.helpers.constructor This option tells the template that instead of returning a string, it should return the "render context", otherwise known as an instance of `vash.helpers.constructor` ([Helper System][]). onRenderEnd @lvl2() ------------------- tpl(model, { onRenderEnd: function(){} }) -> string This option is effectively a callback for once primary execution of the rendering template has finished. The arguments passed to the callback are: `( err, html )`, where `err` is always `null` (for now), and `html` is the render context (instance of `vash.helpers.constructor`). This callback is not required, and is only called if defined (and has no default definition). The [Layout Helpers][] use this to know when all includes, prepends, appends, blocks, and extend calls have finished. [onRenderEnd][] can also be defined as a property of the model: var model = { hey: 'what', onRenderEnd: function(err, ctx){ ... } } Helper System @lvl1() =============== 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: 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:@@html.echo('hello!')
output:hello!
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 could be accessed via `html.mdHref("This is a holdup!")`. Built-in Helpers @lvl1() ======================== vash.helpers.raw @lvl2() ------------------------ 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 text in this function. For an example, see [HTML Escaping][]; vash.helpers.escape @lvl2() --------------------------- 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 @lvl2() ----------------------------- 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][--target-namespace] using [vash(1)][]. Layout Helpers @lvl1() ====================== Vash provides a relatively simple but powerful view engine whose API is borrowed directly from [Jade][]. Below is the API, but an example can be found at [vash-express-example][]. Callbacks are used to maintain compatibility with typical JS syntax. When running in [nodejs][] and using [express][], Vash will automatically resolve and load templates using the same conventions as express itself, specifically [app.engine][]. When in the browser, Vash uses the same rules, but looks in [vash.helpers.tplcache][] instead. [nodejs]: http://nodejs.org [express]: http://expressjs.com [app.engine]: http://expressjs.com/api.html#app.engine [Jade]: http://jade-lang.com [vash-express-example]: https://github.com/kirbysayshi/vash-express-example/tree/master/views [layout.vash]: https://github.com/kirbysayshi/vash-express-example/blob/master/views/layout.vash [Layout.vash]: https://github.com/kirbysayshi/vash-express-example/blob/master/views/layout.vash @function helpersDisclaimer(){ @:_Tech note: due to the way JS scoping works, the `model` parameter of the `cb` function must be explicitely defined as above if it is referenced in the content. This may change in a future version of Vash._ } vash.helpers.extend @lvl2() --------------------------- vash.helpers.extend(parent_path, cb) This is Vash's main form of inheritance for view templates. `parent_path` is the location or name of the template to be extended. A template can define various locations in itself that can be [overridden](#vash-helpers-block) or [added to](#vash-helpers-append). In addition, a template that calls `extend` can even be extended itself! In the following example, this template extends another named [layout.vash][]. [Layout.vash][] defines an empty [block](#vash-helpers-block) named 'content', which is overrided in this example. @@html.extend('layout', function(model){ @@html.block('content', function(model){Hello, I'm default content. It's nice to meet you.
}) @helpersDisclaimer() vash.helpers.append @lvl2() --------------------------- vash.helpers.append(name, cb) [vash.helpers.append][] is a way to control the content of a block from within an extending template. In this way, it allows templates to invert control over content "above" them. An example is a navigation area. Perhaps there is a default navigation list that templates can add to: // layout.vash' );
if( helpers.config.highlighter ){
this.buffer.push( helpers.config.highlighter(lang, cbOutLines.join('')).value );
} else {
this.buffer.push( cbOutLines );
}
this.buffer.push( '
' );
// returning is allowed, but could cause surprising effects. A return
// value will be directly added to the output directly following the above.
}
A `Mark` is effectively a placeholder that can be used to literally mark the rendered content, and later do something with that mark. Possibilities include inserting content at the mark, deleting content that follows a mark, and more. It is an internal constructor that is only ever created through the `Buffer#mark` method within a helper. Examples of `Mark` usage can be found in the [layout helpers code][].
[layout helpers code]: https://github.com/kirbysayshi/vash/blob/master/src/vhelpers.layout.js
TODO: Explain the Buffer methods:
* mark
* fromMark
* spliceMark
* empty
* push
* pushConcat
* indexOf
* lastIndexOf
* splice
* index
* flush
* toString
* toHtmlString
Precompiling Templates @lvl1()
==============================
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 `eval`ed or sent to a remote client. For example:
Hello
Compiles to a function: function anonymous(model,html,__vopts,vash) { var __vbuffer = html.buffer; html.options = __vopts; model = model || {}; __vbuffer.push('\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('\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. Note: this assumes that `vash` is available globally. A future version of Vash will hopefully remove this assumption. Vash Runtime (Browser) @lvl1() ==================== 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 only the runtime must be sent. The runtime includes all helpers and a few standard functions, such as [HTML Escaping][]. There are two runtime builds: * [vash-runtime.min.js][]: This is the basic runtime. It contains everything a standard Vash template needs to execute. * [vash-runtime-all.min.js][]: This also includes the [Layout Helpers][]. It is roughly twice as large as `vash-runtime.min.js`. Unless you're using the Vash view system in the browser, this is probably not necessary. If you're in a Browserify-like environemnt, you should be able to: ```js var vashruntime = require('vash/runtime'); ``` ..and have access to the [Runtime API][]. [vash-runtime.min.js]: https://github.com/kirbysayshi/vash/blob/master/build/vash-runtime.min.js [vash-runtime-all.min.js]: https://github.com/kirbysayshi/vash/blob/master/build/vash-runtime-all.min.js Compile-time API @lvl1() ============= vash.compile @lvl2() ----------------------------------------------- vash.compile(str_template, opt_options) -> Function At its 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 @lvl2() ----------------------------------------------------- vash.compileHelper(str_template, opt_options) -> Object See [Compiled Helpers][] for more detail. vash.compileBatch @lvl2() ---------------------------------------------------- vash.compileBatch(str_template, opt_options) -> Object 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