This repository has been archived on 2018-10-12. You can view files and clone it, but cannot push or open issues or pull requests.
node-task/node_modules/dust/index.html

1078 lines
38 KiB
HTML

<!DOCTYPE HTML><html><head><title>dust</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono:regular&subset=latin" rel="stylesheet" type="text/css"><style type="text/css">body {
font-family: 'Georgia', serif;
font-size: 18px;
margin: 0;
padding: 0;
}
p, h4, h3, .content ul {
line-height: 26px;
margin-top: 26px;
margin-bottom: 26px;
}
.content ul li {
margin-top: 13px;
margin-bottom: 13px;
}
h1, h2 {
line-height: 48px;
font-size: 32px;
font-weight: normal;
margin: 8px 0 8px 2%;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 1em;
}
h1, h2, pre, code, .console, .status, #nav, #tagline {
font-family: 'Droid Sans Mono', 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
}
a:link, a:visited {
color: #ef674a;
}
p code {
font-size: 16px;
line-height: 16px;
}
pre, .console {
background-color: #191919;
white-space: pre-wrap;
word-wrap: break-word;
}
.console {
font-size: 16px;
height: 270px;
color: #dddddd;
margin-top: 26px;
margin-bottom: 26px;
border: 1px solid #888;
resize: auto;
overflow: auto;
padding: 2px;
}
textarea {
width: 100%;
display: block;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#nav {
position: fixed;
top: 18px;
right: 2%;
font-size: 22px;
z-index: 99;
}
#nav a:link, #nav a:visited {
color: #eaf2d9;
}
#nav a {
text-decoration: none;
margin-left: 17px;
}
#nav a:last {
margin: 0;
}
#tagline {
position: absolute;
display: none;
top: 24px;
font-size: 14px;
}
#guide pre {
font-size: 16px;
line-height: 26px;
color: #dddddd;
padding: 26px;
margin: 26px 0;
}
#header, #demo {
clear: both;
}
.ok {
background-color: green;
}
.error {
background-color: red;
}
.pending {
background-color: yellow;
}
.status {
font-size: 14px;
padding: 2px;
margin-top: -24px;
}
.header, .content {
clear: both;
width: 100%;
overflow: hidden;
color: #ede6da;
}
.header {
clear: both;
width: 100%;
-webkit-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4);
-moz-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4);
background-color: #581406;
}
.content {
background-color: #2d2929;
}
.left {
float: left;
width: 100%;
position: relative;
-webkit-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4);
-moz-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4);
}
.content .left, .header .left {
right: 50%;
}
.content .left {
background-color: #272121;
}
.header, .col1, .col2 {
float: left;
position: relative;
overflow: hidden;
}
.col1 {
width: 96%;
left: 2%;
}
.left .header {
width: 100%;
left: 50%;
}
.left .col1 {
width: 46%;
left: 52%;
}
.left .col2 {
width: 46%;
left: 56%;
}
.docked {
position: fixed;
width: 100%;
top: 0;
background-color: hsla(10, 87%, 18%, 0.80);
z-index: 5;
}
code .keyword { font-weight: bold; color: #dd7522 }
code .string, code .regexp { color: #669933 }
code .class, code .special { }
code .number { color: #eddd3d }
code .comment { color: grey }</style><script src="vendor/ecma.js"></script><script src="vendor/jquery.min.js"></script><script src="vendor/jsdump.js"></script><script src="vendor/beautify.js"></script><script src="lib/dust.js"></script><script src="lib/parser.js"></script><script src="lib/compiler.js"></script><script src="test/examples.js"></script><script src="test/uutest.js"></script><script src="test/core.js"></script><script type="text/javascript">(function(){dust.register("select",body_0);function body_0(chk,ctx){return chk.write("<select style=\"clear: both;\">").section(ctx.get("examples"),ctx,{"block":body_1},null).write("</select>");}function body_1(chk,ctx){return chk.write("<option ").reference(ctx.get("selected"),ctx,"h").write(" value=\"").helper("idx",ctx,{"block":body_2},null).write("\">").reference(ctx.get("name"),ctx,"h").write("</option>");}function body_2(chk,ctx){return chk.reference(ctx.getPath(true,[]),ctx,"h");}return body_0;})();</script><script type="text/javascript">jsDump.parsers['function'] = function(fn) {
return fn.toString();
}
function renderDemo() {
var tmpl = dust.cache["demo"],
source = $('#input-context').val();
$('#output-text').empty();
if (tmpl && source) {
setPending('#input-context');
setPending('#output-text');
try {
eval("var context = " + source + ";");
if (typeof context === 'function') {
context = context();
}
dust.stream("demo", context)
.on('data', function(data) {
$('#output-text').append(dust.escapeHtml(data));
})
.on('end', function() {
setOkay('#input-context');
setOkay('#output-text');
})
.on('error', function(err) {
setError('#input-context', err);
});
} catch(err) {
setError('#input-context', err);
}
}
}
function setOkay(sel) {
$(sel).next()
.removeClass('pending')
.addClass('ok')
.html('Ready');
}
function setPending(sel) {
$(sel).next()
.removeClass('ok')
.removeClass('error')
.addClass('pending')
.html('Pending');
}
function setError(sel, err) {
$(sel).next()
.removeClass('pending')
.addClass('error')
.html(err.toString());
}
function dump(obj) {
return js_beautify(jsDump.parse(obj), {
indent_size: 2
});
}
function runSuite() {
var suite = new uutest.Suite({
start: function() {
$('#test-console').empty();
},
pass: function() {
$('#test-console').append(".");
},
fail: function() {
$('#test-console').append("F");
},
done: function(passed, failed, elapsed) {
$('#test-console').append("\n");
$('#test-console').append(passed + " passed " + failed + " failed " + "(" + elapsed + "ms)");
this.errors.forEach(function(err) {
$('#test-console').append("\n");
$('#test-console').append(dust.escapeHtml(dumpError(err)));
});
}
});
coreSetup(suite, dustExamples.slice(1), dust);
suite.run();
}
function dumpError(err) {
var out = err.testName + " -> ";
if (!err.message) {
err.message = jsDump.parse(err.expected)
+ " " + err.operator + " " + jsDump.parse(err.actual);
}
return out + err.stack;
}
$(document).ready(function() {
dustExamples.forEach(function(ex) {
dust.loadSource(dust.compile(ex.source, ex.name));
});
runSuite();
$('#tagline').empty().show().css({left: ($(window).width() * .02) + 125});
dust.loadSource(dust.compile(dustExamples[0].source, "intro"));
dust.stream("intro", dustExamples[0].context())
.on('data', function(data) {
$('#tagline').append(data);
})
.on('end', function() {
$('#tagline').delay(500).fadeOut('slow');
});
dust.render("select", {
examples: dustExamples,
selected: function(chk, ctx) {
if (ctx.current().name === "replace") return "selected";
}
}, function(err, output) {
$('#select').html(output);
});
$('#select > select').change(function() {
var idx = $(this).val();
$('#input-source').val(dustExamples[idx].source);
$('#input-context').val(dump(dustExamples[idx].context));
$('#input-source').change();
});
$('#input-source').change(function() {
setPending('#input-source');
try {
var compiled = dust.compile($(this).val(), "demo");
dust.loadSource(compiled);
$('#output-js').text(js_beautify(compiled, {
indent_size: 2
}));
setOkay('#input-source');
} catch(err) {
setError('#input-source', err);
return;
}
renderDemo();
});
$('#input-context').change(renderDemo);
var sections = $("body > div");
var cur_id;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop === 0) {
cur_id = undefined;
$('.docked').remove();
return;
}
sections.each(function(idx, section) {
var sectionTop = section.offsetTop,
sectionBottom = sectionTop + section.offsetHeight;
if (scrollTop >= sectionTop && scrollTop < sectionBottom) {
var $hdr = $(section).find('.header').clone();
if (section.id !== cur_id) {
cur_id = section.id;
$('.docked').remove();
$hdr.appendTo('body');
$hdr.addClass('docked');
}
return false;
}
});
});
$('#select > select').change();
$(window).scroll();
});</script></head><body><div id="dust" class="content"><div class="left"><div class="header"><h1>{dust}</h1><span id="tagline">asynchronous streaming templates for the browser and node.js</span></div><div id="nav"><a href="#dust">home</a><a href="#guide">guide</a><a href="#tests">tests</a><a href="#about">about</a><a href="http://github.com/akdubya/dustjs">code</a></div><div class="col1"><p>1. Select a template <span id="select"></span> or write your own:</p><textarea id="input-source" class="console"></textarea><div class="status ok">Ready</div><p>2. The compiled template registers itself by name:</p><pre class="console"><code id="output-js"></code></pre><p>When you're done messing around have a look at the guide.</p></div><div class="col2"><p>3. Control template behavior with contexts and helpers:</p><textarea id="input-context" class="console"></textarea><div class="status ok">Ready</div><p>4. Render or stream the result:</p><pre id="output-text" class="console"></pre></div></div></div><div id="guide" class="content"><div class="left"><div class="header"><h2>{guide}</h2></div><div id="syntax" class="col1"><p>Dust is a JavaScript templating engine designed to provide a clean separation between presentation and logic without sacrificing ease of use. It is particularly well-suited for asynchronous and streaming applications.</p>
<h3>Syntax</h3>
<p>Dust templates use two types of tags: <em>keys</em> and <em>sections</em>. Keys reference fields within the current view context. You can think of them as placeholders that allow the context to insert data into the template. Sections accept template blocks that may be enumerated, filtered or transformed in various ways.</p>
<h3>Keys</h3>
<p>To reference a key from the view context within the template, enclose the key in curly braces. For example, given the template below:</p>
<pre><code>Hello {name}!
</code></pre>
<p>And the following view context:</p>
<pre><code>{ name: "Fred" }
</code></pre>
<p>The resulting output would be:</p>
<pre><code>Hello Fred!
</code></pre>
<p>If the <em>name</em> key cannot be found in the view, Dust outputs an empty string:</p>
<pre><code>Hello !
</code></pre>
<p>Generally, Dust casts whatever values it finds to strings. If Dust encounters a handler function it calls the function, passing in the current state of the template.</p>
<h4>Filters</h4>
<p>By default, the content of all key tags is HTML escaped, so assuming the <em>name</em> key above resolves to a dangerous script tag:</p>
<pre><code>&lt;script&gt;alert('I am evil!')&lt;/script&gt;
</code></pre>
<p>This would be rendered as:</p>
<pre><code>&amp;lt;script&amp;gt;alert('I am evil!')&amp;lt;/script&amp;gt;
</code></pre>
<p>To disable auto-escaping, append a pipe character '|' and an 's' to the end of the tag identifier, like so:</p>
<pre><code>Hello {name|s}
</code></pre>
<p>There are several other built-in filters: <code>h</code> forces HTML escaping, <code>j</code> escapes JavaScript strings, <code>u</code> proxies to JavaScript's built-in <code>encodeURI</code>, and <code>uc</code> proxies to JavaScript's <code>encodeURIComponent</code>. Filters can also be chained together like so:</p>
<pre><code>Hello {name|s|h|u}
</code></pre>
<p>When chained in this manner, filters are applied from left to right. Filters do not accept arguments; if you need more sophisticated behavior use a section tag instead.</p>
<h3>Sections</h3>
<p>Keys are fine for simple lookups, but suppose the view context contains a <em>friends</em> field which resolves to an array of objects containing <em>name</em> and <em>age</em> fields. This is where section tags are useful.</p>
<pre><code>{#friends}
{name}, {age}{~n}
{/friends}
</code></pre>
<p>Here, the section begins with <code>{#friends}</code> and ends with <code>{/friends}</code>. Dust's default behavior is to enumerate over the array, passing each object in the array to the block. With a the following view context:</p>
<pre><code>{
friends: [
{ name: "Moe", age: 37 },
{ name: "Larry", age: 39 },
{ name: "Curly", age: 35 }
]
}
</code></pre>
<p>The output is as one might expect:</p>
<pre><code>Moe, 37
Larry, 39
Curly, 35
</code></pre>
<p>When <em>friends</em> resolves to a value or object instead of an array, Dust sets the current context to the value and renders the block one time. If <em>friends</em> resolves to a custom handler function, the function is given control over the section's behavior.</p>
<p>Dust outputs nothing if the friends key is empty or nonexistent. Let's change that by inserting an <code>{:else}</code> tag, which tells Dust to render an alternate template block when a section key resolves to a falsy value:</p>
<pre><code>{#friends}
{name}, {age}{~n}
{:else}
You have no friends!
{/friends}
</code></pre>
<p>Now when the friends key is empty or nonexistent we get the following:</p>
<pre><code>You have no friends!
</code></pre>
<p>Internally, Dust builds a stack of contexts as templates delve deeper into nested sections. If a key is not found within the current context, Dust looks for the key within the parent context, and its parent, and so on.</p>
<p>Self-closing section tags are allowed, so the template code below is permissible (although in this case it won't render anything):</p>
<pre><code>{#friends/}
</code></pre>
<h4>Paths</h4>
<p>Paths allow you to reference keys relative to the current context. </p>
<pre><code>{#names}{.} {/names}
</code></pre>
<p>The dot notation above lets the template reference the current context implicitly, so given an array of strings:</p>
<pre><code>{ names: ["Moe", "Larry", "Curly"] }
</code></pre>
<p>The template block outputs each string in the array.</p>
<pre><code>Moe Larry Curly
</code></pre>
<p>Paths can also be used to reach into nested contexts:</p>
<pre><code>{foo.bar}
</code></pre>
<p>Or to constrain lookups to the current section scope:</p>
<pre><code>{.foo}
</code></pre>
<p>To avoid brittle and confusing references, paths never backtrack up the context stack. If you need to drill into a key available within the parent context, pass the key as a parameter.</p>
<h4>Inline Parameters</h4>
<p>Inline parameters appear within the section's opening tag. Parameters are separated by a single space. By default, inline parameters merge values into the section's view context:</p>
<pre><code>{#profile bar="baz" bing="bong"}
{name}, {bar}, {bing}
{/profile}
</code></pre>
<p>Assuming <em>name</em> within the profile section resolves to "Fred", the output would be:</p>
<pre><code>Fred, baz, bong
</code></pre>
<p>Inline parameters may be used to alias keys that conflict between parent and child contexts:</p>
<pre><code>{name}{~n}
{#profile root_name=name}
{name}, {root_name}
{/profile}
</code></pre>
<p>Note here that we're passing in a key rather than a string literal. If the context is as follows:</p>
<pre><code>{
name: "Foo",
profile: {
name: "Bar"
}
}
</code></pre>
<p>The output will be:</p>
<pre><code>Foo
Bar, Foo
</code></pre>
<p>Parameters accept interpolated string literals as values:</p>
<pre><code>{#snippet id="{name}_id"/}
</code></pre>
<h4>Body Parameters</h4>
<p>Unlike inline parameters, which modify the context, body parameters pass named template blocks to handler functions. Body parameters are useful for implementing striping or other complex behaviors that might otherwise involve manually assembling strings within your view functions. The only body parameter with default behavior is the <code>{:else}</code> tag as seen above.</p>
<h4>Contexts</h4>
<p>Normally, upon encountering a section tag Dust merges the section's context with the parent context. Sometimes it can be useful to manually set the context provided to a section. Sections accept a context argument for this purpose:</p>
<pre><code>{#list:projects}{name}{/list}
</code></pre>
<p>Here, we're providing an array of <em>projects</em> to the <em>list</em> section, which might be a special helper defined on the view. If <em>list</em> is not a function but some other value instead, its parent context is simply set to <em>projects</em>.</p>
<h4>Special Sections</h4>
<p>In addition to the standard hashed (<code>#</code>) section tag, Dust provides a few section tags with special semantics, namely the <em>exists</em> tag (<code>?</code>), the <em>notexists</em> tag (<code>^</code>), and the context helpers tag (<code>@</code>). These tags make it easier to work with plain JSON data without additional helpers.</p>
<p>The exists and notexists sections check for the existence (in the falsy sense) of a key within the current context. They do not alter the current context, making it possible to, for instance, check that an array is non-empty before wrapping it in HTML list tags:</p>
<pre><code>{?tags}
&lt;ul&gt;
{#tags}
&lt;li&gt;{.}&lt;/li&gt;
{/tags}
&lt;/ul&gt;
{:else}
No Tags!
{/tags}
</code></pre>
<p>Unlike regular sections, conditional sections do not evaluate functions defined on the view. In those cases you'll still have to write your own handlers.</p>
<p>The context helpers tag provides a couple of convenience functions to support iteration. The <code>sep</code> tag prints the enclosed block for every value except for the last. The <code>idx</code> tag passes the numerical index of the current element to the enclosed block.</p>
<pre><code>{#names}{.}{@idx}{.}{/idx}{@sep}, {/sep}{/names}
</code></pre>
<p>The template above might output something like:</p>
<pre><code>Moe0, Larry1, Curly2
</code></pre>
<h3>Partials</h3>
<p>Partials, also known as template includes, allow you to compose templates at runtime.</p>
<pre><code>{&gt;profile/}
</code></pre>
<p>The block above looks for a template named "profile" and inserts its output into the parent template. Like sections, partials inherit the current context. And like sections, partials accept a context argument:</p>
<pre><code>{&gt;profile:user/}
</code></pre>
<p>Partial tags also accept string literals and interpolated string literals as keys:</p>
<pre><code>{&gt;"path/to/comments.dust.html"/}
{&gt;"posts/{type}.dust.html"/}
</code></pre>
<p>This is useful when you're retrieving templates from the filesystem and the template names wouldn't otherwise be valid identifiers, or when selecting templates dynamically based on information from the view context.</p>
<h3>Blocks and Inline Partials</h3>
<p>Often you'll want to have a template inherit the bulk of its content from a common base template. Dust solves this problem via blocks and inline partials. When placed within a template, blocks allow you to define snippets of template code that may be overriden by any templates that reference this template:</p>
<pre><code>Start{~n}
{+title}
Base Title
{/title}
{~n}
{+main}
Base Content
{/main}
{~n}
End
</code></pre>
<p>Notice the special syntax for blocks: <code>{+block} ... {/block}</code>. When this template is rendered standalone, Dust simply renders the content within the blocks:</p>
<pre><code>Start
Base Title
Base Content
End
</code></pre>
<p>But when the template is invoked from another template that contains inline partial tags (<code>{&lt;snippet} ... {/snippet}</code>):</p>
<pre><code>{&gt;base_template/}
{&lt;title}
Child Title
{/title}
{&lt;main}
Child Content
{/main}
</code></pre>
<p>Dust overrides the block contents of the base template:</p>
<pre><code>Start
Child Title
Child Content
End
</code></pre>
<p>A block may be self-closing (<code>{+block/}</code>), in which case it is not displayed unless a calling template overrides the content of the block. Inline partials never output content themselves, and are always global to the template in which they are defined, so the order of their definition has no significance. They are passed to all templates invoked by the template in which they are defined.</p>
<p>Note that blocks can be used to render inline partials that are defined within the same template. This is useful when you want to use the same template to serve AJAX requests and regular requests:</p>
<pre><code>{^xhr}
{&gt;base_template/}
{:else}
{+main/}
{/xhr}
{&lt;title}
Child Title
{/title}
{&lt;main}
Child Content
{/main}
</code></pre>
<h3>Static Text</h3>
<p>The Dust parser is finely tuned to minimize the amount of escaping that needs to be done within static text. Any text that does not closely resemble a Dust tag is considered static and will be passed through untouched to the template's output. This makes Dust suitable for use in templating many different formats. In order to be recognized as such, Dust tags should not contain extraneous whitespace and newlines.</p>
<h4>Special Characters</h4>
<p>Depending on whitespace and delimeter settings, it is sometimes necessary to include escape tags within static text. Escape tags begin with a tilde (<code>~</code>), followed by a key identifying the desired escape sequence. Currently newline (<code>n</code>), carriage return (<code>r</code>), space (<code>s</code>), left brace (<code>lb</code>) and right brace (<code>rb</code>) are supported. For example:</p>
<pre><code>Hello World!{~n}
</code></pre>
<p>Inserts a newline after the text. By default, Dust compresses whitespace by eliminating newlines and indentation. This behavior can be toggled at compile time.</p>
<h4>Comments</h4>
<p>Comments, which do not appear in template output, begin and end with a bang (<code>!</code>):</p>
<pre><code>{!
Multiline
{#foo}{bar}{/foo}
!}
{!before!}Hello{!after!}
</code></pre>
<p>The template above would render as follows:</p>
<pre><code>Hello
</code></pre></div><div id="api" class="col2"><p>A pure JavaScript library, Dust is runs in both browser-side and server-side environments. Dust templates are compiled and then loaded where they are needed along with the runtime library. The library doesn't make any assumptions about how templates are loaded; you are free to integrate templating into your environment as you see fit.</p>
<h3>Installation</h3>
<p>To run Dust within Node.js, first install via <a href="http://github.com/isaacs/npm">npm</a>:</p>
<pre><code>npm install dust
</code></pre>
<p>Then, within your Node script or the REPL:</p>
<pre><code>var dust = require('dust');
</code></pre>
<p>This will import everything needed to parse, compile and render templates. To render Dust templates in the browser, grab the runtime distribution and include it in your script tags along with your compiled templates:</p>
<pre><code>&lt;script src="dust-core-0.3.0.min.js"&gt;&lt;/script&gt;
&lt;script src="compiled_templates.js"&gt;&lt;/script&gt;
</code></pre>
<p>Include the full distribution if you want to compile templates within the browser (as in the online demo):</p>
<pre><code>&lt;script src="dust-full-0.3.0.min.js"&gt;&lt;/script&gt;
</code></pre>
<p>Precompilation is the recommended approach for general use.</p>
<h3>Compiling Templates</h3>
<p>Use <code>dust.compile</code> to compile a template body into a string of JavaScript source code:</p>
<pre><code>var compiled = dust.compile("Hello {name}!", "intro");
</code></pre>
<p>The variable <code>compiled</code> now contains the following string:</p>
<pre><code>'(function(){dust.register("intro",body_0) ...'
</code></pre>
<p>If you save this source to a file and include the file in your HTML script tags, the compiled template will automatically register itself with the local runtime, under the name "intro". To evaluate a compiled template string manually, use <code>dust.loadSource</code>:</p>
<pre><code>dust.loadSource(compiled);
</code></pre>
<p>The template is now available within the <code>dust.cache</code> object.</p>
<h3>Rendering Templates</h3>
<p>The rendering engine provides both callback and streaming interfaces.</p>
<h4>The Callback Interface</h4>
<p>To render a template, call <code>dust.render</code> with the template name, a context object and a callback function:</p>
<pre><code>dust.render("intro", {name: "Fred"}, function(err, out) {
console.log(out);
});
</code></pre>
<p>The code above will write the following to the console:</p>
<pre><code>Hello Fred!
</code></pre>
<h4>The Streaming Interface</h4>
<p>Templates may also be streamed. <code>dust.stream</code> returns a handler very similar to a Node <code>EventEmitter</code>:</p>
<pre><code>dust.stream("index", context)
.on("data", function(data) {
console.log(data);
})
.on("end", function() {
console.log("I'm finished!");
})
.on("error", function(err) {
console.log("Something terrible happened!");
});
</code></pre>
<p>When used with specially crafted context handlers, the streaming interface provides chunked template rendering.</p>
<h3>Contexts</h3>
<p>The context is a special object that handles variable lookups and controls template behavior. It is the interface between your application logic and your templates. The context can be visualized as a stack of objects that grows as we descend into nested sections:</p>
<pre><code>global --&gt; { helper: function() { ... }, ... }
root --&gt; { profile: { ... }, ... }
profile --&gt; { friends: [ ... ], ... }
friends[0] --&gt; { name: "Jorge", ... }
</code></pre>
<p>When looking up a key, Dust searches the context stack from the bottom up. There is no need to merge helper functions into the template data; instead, create a base context onto which you can push your local template data:</p>
<pre><code>// Set up a base context with global helpers
var base = dust.makeBase({
sayHello: function() { return "Hello!" }
});
// Push to the base context at render time
dust.render("index", base.push({foo: "bar"}), function(err, out) {
console.log(out);
});
</code></pre>
<p>Dust does not care how your reference objects are built. You may, for example, push prototyped objects onto the stack. The system leaves the <code>this</code> keyword intact when calling handler functions on your objects.</p>
<h3>Handlers</h3>
<p>When Dust encounters a function in the context, it calls the function, passing in arguments that reflect the current state of the template. In the simplest case, a handler can pass a value back to the template engine:</p>
<pre><code>{
name: function() {
return "Bob";
}
}
</code></pre>
<h4>Chunks</h4>
<p>But handlers can do much more than return values: they have complete control over the flow of the template, using the same API Dust uses internally. For example, the handler below writes a string directly to the current template chunk:</p>
<pre><code>{
name: function(chunk) {
return chunk.write("Bob");
}
}
</code></pre>
<p>A <code>Chunk</code> is a Dust primitive for controlling the flow of the template. Depending upon the behaviors defined in the context, templates may output one or more chunks during rendering. A handler that writes to a chunk directly must return the modified chunk.</p>
<h4>Accessing the Context</h4>
<p>Handlers have access to the context object:</p>
<pre><code>{
wrap: function(chunk, context) {
return chunk.write(context.get("foo"));
}
}
</code></pre>
<p><code>context.get("foo")</code> searches for <em>foo</em> within the context stack. <code>context.current()</code> retrieves the value most recently pushed onto the context stack.</p>
<h4>Accessing Body Parameters</h4>
<p>The <code>bodies</code> object provides access to any bodies defined within the calling block.</p>
<pre><code>{#guide}foo{:else}bar{/guide}
</code></pre>
<p>The template above will either render "foo" or "bar" depending on the behavior of the handler below:</p>
<pre><code>{
guide: function(chunk, context, bodies) {
if (secret === 42) {
return chunk.render(bodies.block, context);
} else {
return chunk.render(bodies['else'], context);
}
}
}
</code></pre>
<p><code>bodies.block</code> is a special parameter that returns the default (unnamed) block. <code>chunk.render</code> renders the chosen block.</p>
<h4>Accessing Inline Parameters</h4>
<p>The <code>params</code> object contains any inline parameters passed to a section tag:</p>
<pre><code>{
hello: function(chunk, context, bodies, params) {
if (params.greet === "true") {
return chunk.write("Hello!");
}
return chunk;
}
}
</code></pre>
<h4>Asynchronous Handlers</h4>
<p>You may define handlers that execute asynchronously and in parallel:</p>
<pre><code>{
type: function(chunk) {
return chunk.map(function(chunk) {
setTimeout(function() {
chunk.end("Async");
});
});
}
}
</code></pre>
<p><code>chunk.map</code> tells Dust to manufacture a new chunk, reserving a slot in the output stream before continuing on to render the rest of the template. You must (eventually) call <code>chunk.end()</code> on a mapped chunk to weave its content back into the stream.</p>
<p><code>chunk.map</code> provides a convenient way to split up templates rendered via <code>dust.stream</code>. For example, you might wrap the head of an HTML document in a special <code>{#head} ... {/head}</code> tag that is flushed to the browser before the rest of the body has finished rendering.</p>
<h3>Reference</h3>
<h4>Compiling</h4>
<pre><code>dust.compile(source, name)
</code></pre>
<p>Compiles <code>source</code> into a JavaScript template string. Registers itself under <code>name</code> when evaluated.</p>
<pre><code>dust.compileFn(source, [name])
</code></pre>
<p>Compiles <code>source</code> directly into a JavaScript function that takes a context and an optional callback (see <code>dust.renderSource</code>). Registers the template under <code>name</code> if this argument is supplied.</p>
<pre><code>dust.optimizers
</code></pre>
<p>Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression:</p>
<pre><code>dust.optimizers.format = function(ctx, node) { return node };
</code></pre>
<h4>Loading</h4>
<pre><code>dust.register(name, fn)
</code></pre>
<p>Used internally to register template function <code>fn</code> with the runtime environment. Override to customize the way Dust caches templates.</p>
<pre><code>dust.onLoad(name, callback(err, out))
</code></pre>
<p>By default Dust returns a "template not found" error when a named template cannot be located in the cache. Override <code>onLoad</code> to specify a fallback loading mechanism (e.g., to load templates from the filesystem or a database).</p>
<pre><code>dust.loadSource(source, [filename])
</code></pre>
<p>Evaluates compiled <code>source</code> string. In Node.js, evaluates <code>source</code> as if it were loaded from <code>filename</code>. <code>filename</code> is optional.</p>
<h4>Rendering</h4>
<pre><code>dust.render(name, context, callback(error, output))
</code></pre>
<p>Renders the named template and calls <code>callback</code> on completion. <code>context</code> may be a plain object or an instance of <code>dust.Context</code>.</p>
<pre><code>dust.stream(name, context)
</code></pre>
<p>Streams the named template. <code>context</code> may be a plain object or an instance of <code>dust.Context</code>. Returns an instance of <code>dust.Stream</code>.</p>
<pre><code>stream.on("data", listener(data))
stream.on("end", listener)
stream.on("error", listener(error))
</code></pre>
<p>Registers an event listener. Streams accept a single listener for a given event.</p>
<pre><code>dust.renderSource(source, context, [callback(error, output)])
</code></pre>
<p>Compiles and renders <code>source</code>, invoking <code>callback</code> on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required.</p>
<h4>Contexts</h4>
<pre><code>dust.makeBase(object)
</code></pre>
<p>Manufactures a <code>dust.Context</code> instance with its global object set to <code>object</code>.</p>
<pre><code>context.get(key)
</code></pre>
<p>Retrieves the value at <code>key</code> from the context stack.</p>
<pre><code>context.push(head, [index], [length])
</code></pre>
<p>Pushes an arbitrary value onto the context stack and returns a new context instance. Specify <code>index</code> and/or <code>length</code> to enable enumeration helpers.</p>
<pre><code>context.rebase(head)
</code></pre>
<p>Returns a new context instance consisting only of the value at <code>head</code>, plus any previously defined global object.</p>
<pre><code>context.current()
</code></pre>
<p>Returns the <code>head</code> of the context stack.</p>
<h4>Chunks</h4>
<p>The operations below always return a chunk object.</p>
<pre><code>chunk.write(data)
</code></pre>
<p>Writes <code>data</code> to this chunk's buffer.</p>
<pre><code>chunk.map(callback(chunk))
</code></pre>
<p>Creates a new chunk and passes it to <code>callback</code>. Use <code>map</code> to wrap asynchronous functions and to partition the template for streaming.</p>
<pre><code>chunk.end(data)
</code></pre>
<p>Writes <code>data</code> to this chunk's buffer and marks it as flushable. This method <em>must</em> be called on any chunks created via <code>chunk.map</code>. Do <em>not</em> call this method on a handler's main chunk -- <code>dust.render</code> and <code>dust.stream</code> take care of this for you.</p>
<pre><code>chunk.tap(callback)
chunk.untap()
</code></pre>
<p>Convenience methods for applying filters to a stream. See the <em>filter</em> demo for an example.</p>
<pre><code>chunk.render(body, context)
</code></pre>
<p>Renders a template block, such as a default block or an <code>else</code> block. Basically equivalent to <code>body(chunk, context)</code>.</p>
<pre><code>chunk.setError(error)
</code></pre>
<p>Sets an error on this chunk and immediately flushes the output.</p>
<pre><code>chunk.reference(elem, context, auto, filters)
chunk.section(elem, context, bodies, params)
chunk.exists(elem, context, bodies)
chunk.notexists(elem, context, bodies)
chunk.block(elem, context, bodies)
chunk.partial(elem, context)
chunk.helper(name, context, bodies, params)
</code></pre>
<p>These methods implement Dust's default behavior for keys, sections, blocks, partials and context helpers. While it is unlikely you'll need to modify these methods or invoke them from within handlers, the source code may be a useful point of reference for developers.</p>
<h4>Utilities</h4>
<pre><code>dust.filters
</code></pre>
<p>Object containing built-in key filters. Can be customized with additional filters.</p>
<pre><code>dust.helpers
</code></pre>
<p>Object containing the built-in context helpers. These may also be customized.</p>
<pre><code>dust.escapeHtml
</code></pre>
<p>HTML escape function used by <code>dust.filters.h</code>.</p>
<pre><code>dust.escapeJs
</code></pre>
<p>JavaScript string escape function used by <code>dust.filters.j</code>.</p></div></div></div><div id="tests" class="content"><div class="left"><div class="header"><h2>{tests}</h2></div><div class="col1"><p>If the console below indicates an error then we have a problem.</p><pre id="test-console" class="console"></pre></div><div class="col2"><p>Interested in seeing how Dust stacks up against similar templating engines? Have a look at the <a href="benchmark/index.html">live benchmarks</a>.</p></div></div></div><div id="about" class="content"><div class="left"><div class="header"><h2>{about}</h2></div><div class="col1"><p>Why Dust? Why another templating engine when there are so many alternatives? Dust is based on the philosophy that an ideal templating environment should be:</p>
<ul>
<li><strong>Markup-like</strong>: <em>A templating syntax should not encompass operations that are better left to a programming language</em>. Templates should make it easy to format content for presentation while keeping application logic where it belongs: in the application.</li>
<li><strong>Asynchronous</strong>: Template helpers should be callable <em>asynchronously</em> and in <em>parallel</em> so that expensive operations (caching, deferred loading, filtering) can run as the template is being rendered.</li>
<li><strong>Streaming</strong>: Templates should allow (but not require) data to be flushed to the output in user-defined chunks.</li>
<li><strong>Browser and server compatible</strong>: Templates should render in both server and browser environments without hacks or extensive configuration.</li>
<li><strong>Storage agnostic</strong>: <em>The templating engine should not impose a particular loading scheme</em>. Developers should be free to load templates via the filesystem, a database or an army of carrier pigeons.</li>
<li><strong>Composable</strong>: Designers should be able to break presentation markup into manageable components and combine these components at runtime. <em>It should not be necessary to statically link templates or manually assemble 'layouts' inside application code.</em></li>
<li><strong>Format agnostic</strong>: While HTML generation and DOM manipulation are useful in specific instances, a general-purpose template system should not be tied to a particular output format.</li>
<li><strong>Precise</strong>: The parser should be accurate enough that designers rarely have to use escape sequences to achieve the desired result. Similarly, templates shouldn't mysteriously generate or eliminate whitespace.</li>
<li><strong>Safe(r)</strong>: At the very least, the engine should be configurable such that it is reasonably safe to render untrusted templates in a server environment.</li>
<li><strong>Fast</strong>: Server-side templates cannot always be cached. Browser-side templates may be rendered on devices with limited system resources. <em>A template engine should be fast enough to render in real time without bottlenecking its environment</em>.</li>
</ul>
<p>If this list leaves you nodding your head in agreement you should <a href="http://akdubya.github.com/dustjs">give Dust a try</a>.</p></div><div class="col2"><p>Dust was created by <a href="http://github.com/akdubya">akdubya</a>.</p><p>This page is powered by Dust, <a href="http://jquery.com/">jQuery</a>, <a href="http://attacklab.net/showdown/">showdown</a>, <a href="http://jsbeautifier.org/">beautify.js</a>, <a href="http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html">jsDump</a> and <a href="http://github.com/cloudhead/hijs">hijs</a>.</div></div></div><script src="vendor/hijs.js"></script></body></html>