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.
Syntax
Dust templates use two types of tags: keys and sections. 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.
Keys
To reference a key from the view context within the template, enclose the key in curly braces. For example, given the template below:
Hello {name}!
And the following view context:
{ name: "Fred" }
The resulting output would be:
Hello Fred!
If the name key cannot be found in the view, Dust outputs an empty string:
Hello !
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.
Filters
By default, the content of all key tags is HTML escaped, so assuming the name key above resolves to a dangerous script tag:
<script>alert('I am evil!')</script>
This would be rendered as:
<script>alert('I am evil!')</script>
To disable auto-escaping, append a pipe character '|' and an 's' to the end of the tag identifier, like so:
Hello {name|s}
There are several other built-in filters: h
forces HTML escaping, j
escapes JavaScript strings, u
proxies to JavaScript's built-in encodeURI
, and uc
proxies to JavaScript's encodeURIComponent
. Filters can also be chained together like so:
Hello {name|s|h|u}
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.
Sections
Keys are fine for simple lookups, but suppose the view context contains a friends field which resolves to an array of objects containing name and age fields. This is where section tags are useful.
{#friends}
{name}, {age}{~n}
{/friends}
Here, the section begins with {#friends}
and ends with {/friends}
. 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:
{
friends: [
{ name: "Moe", age: 37 },
{ name: "Larry", age: 39 },
{ name: "Curly", age: 35 }
]
}
The output is as one might expect:
Moe, 37
Larry, 39
Curly, 35
When friends 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 friends resolves to a custom handler function, the function is given control over the section's behavior.
Dust outputs nothing if the friends key is empty or nonexistent. Let's change that by inserting an {:else}
tag, which tells Dust to render an alternate template block when a section key resolves to a falsy value:
{#friends}
{name}, {age}{~n}
{:else}
You have no friends!
{/friends}
Now when the friends key is empty or nonexistent we get the following:
You have no friends!
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.
Self-closing section tags are allowed, so the template code below is permissible (although in this case it won't render anything):
{#friends/}
Paths
Paths allow you to reference keys relative to the current context.
{#names}{.} {/names}
The dot notation above lets the template reference the current context implicitly, so given an array of strings:
{ names: ["Moe", "Larry", "Curly"] }
The template block outputs each string in the array.
Moe Larry Curly
Paths can also be used to reach into nested contexts:
{foo.bar}
Or to constrain lookups to the current section scope:
{.foo}
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.
Inline Parameters
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:
{#profile bar="baz" bing="bong"}
{name}, {bar}, {bing}
{/profile}
Assuming name within the profile section resolves to "Fred", the output would be:
Fred, baz, bong
Inline parameters may be used to alias keys that conflict between parent and child contexts:
{name}{~n}
{#profile root_name=name}
{name}, {root_name}
{/profile}
Note here that we're passing in a key rather than a string literal. If the context is as follows:
{
name: "Foo",
profile: {
name: "Bar"
}
}
The output will be:
Foo
Bar, Foo
Parameters accept interpolated string literals as values:
{#snippet id="{name}_id"/}
Body Parameters
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 {:else}
tag as seen above.
Contexts
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:
{#list:projects}{name}{/list}
Here, we're providing an array of projects to the list section, which might be a special helper defined on the view. If list is not a function but some other value instead, its parent context is simply set to projects.
Special Sections
In addition to the standard hashed (#
) section tag, Dust provides a few section tags with special semantics, namely the exists tag (?
), the notexists tag (^
), and the context helpers tag (@
). These tags make it easier to work with plain JSON data without additional helpers.
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:
{?tags}
<ul>
{#tags}
<li>{.}</li>
{/tags}
</ul>
{:else}
No Tags!
{/tags}
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.
The context helpers tag provides a couple of convenience functions to support iteration. The sep
tag prints the enclosed block for every value except for the last. The idx
tag passes the numerical index of the current element to the enclosed block.
{#names}{.}{@idx}{.}{/idx}{@sep}, {/sep}{/names}
The template above might output something like:
Moe0, Larry1, Curly2
Partials
Partials, also known as template includes, allow you to compose templates at runtime.
{>profile/}
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:
{>profile:user/}
Partial tags also accept string literals and interpolated string literals as keys:
{>"path/to/comments.dust.html"/}
{>"posts/{type}.dust.html"/}
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.
Blocks and Inline Partials
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:
Start{~n}
{+title}
Base Title
{/title}
{~n}
{+main}
Base Content
{/main}
{~n}
End
Notice the special syntax for blocks: {+block} ... {/block}
. When this template is rendered standalone, Dust simply renders the content within the blocks:
Start
Base Title
Base Content
End
But when the template is invoked from another template that contains inline partial tags ({<snippet} ... {/snippet}
):
{>base_template/}
{<title}
Child Title
{/title}
{<main}
Child Content
{/main}
Dust overrides the block contents of the base template:
Start
Child Title
Child Content
End
A block may be self-closing ({+block/}
), 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.
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:
{^xhr}
{>base_template/}
{:else}
{+main/}
{/xhr}
{<title}
Child Title
{/title}
{<main}
Child Content
{/main}
Static Text
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.
Special Characters
Depending on whitespace and delimeter settings, it is sometimes necessary to include escape tags within static text. Escape tags begin with a tilde (~
), followed by a key identifying the desired escape sequence. Currently newline (n
), carriage return (r
), space (s
), left brace (lb
) and right brace (rb
) are supported. For example:
Hello World!{~n}
Inserts a newline after the text. By default, Dust compresses whitespace by eliminating newlines and indentation. This behavior can be toggled at compile time.
Comments
Comments, which do not appear in template output, begin and end with a bang (!
):
{!
Multiline
{#foo}{bar}{/foo}
!}
{!before!}Hello{!after!}
The template above would render as follows:
Hello
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.
Installation
To run Dust within Node.js, first install via npm:
npm install dust
Then, within your Node script or the REPL:
var dust = require('dust');
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:
<script src="dust-core-0.3.0.min.js"></script>
<script src="compiled_templates.js"></script>
Include the full distribution if you want to compile templates within the browser (as in the online demo):
<script src="dust-full-0.3.0.min.js"></script>
Precompilation is the recommended approach for general use.
Compiling Templates
Use dust.compile
to compile a template body into a string of JavaScript source code:
var compiled = dust.compile("Hello {name}!", "intro");
The variable compiled
now contains the following string:
'(function(){dust.register("intro",body_0) ...'
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 dust.loadSource
:
dust.loadSource(compiled);
The template is now available within the dust.cache
object.
Rendering Templates
The rendering engine provides both callback and streaming interfaces.
The Callback Interface
To render a template, call dust.render
with the template name, a context object and a callback function:
dust.render("intro", {name: "Fred"}, function(err, out) {
console.log(out);
});
The code above will write the following to the console:
Hello Fred!
The Streaming Interface
Templates may also be streamed. dust.stream
returns a handler very similar to a Node EventEmitter
:
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!");
});
When used with specially crafted context handlers, the streaming interface provides chunked template rendering.
Contexts
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:
global --> { helper: function() { ... }, ... }
root --> { profile: { ... }, ... }
profile --> { friends: [ ... ], ... }
friends[0] --> { name: "Jorge", ... }
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:
// 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);
});
Dust does not care how your reference objects are built. You may, for example, push prototyped objects onto the stack. The system leaves the this
keyword intact when calling handler functions on your objects.
Handlers
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:
{
name: function() {
return "Bob";
}
}
Chunks
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:
{
name: function(chunk) {
return chunk.write("Bob");
}
}
A Chunk
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.
Accessing the Context
Handlers have access to the context object:
{
wrap: function(chunk, context) {
return chunk.write(context.get("foo"));
}
}
context.get("foo")
searches for foo within the context stack. context.current()
retrieves the value most recently pushed onto the context stack.
Accessing Body Parameters
The bodies
object provides access to any bodies defined within the calling block.
{#guide}foo{:else}bar{/guide}
The template above will either render "foo" or "bar" depending on the behavior of the handler below:
{
guide: function(chunk, context, bodies) {
if (secret === 42) {
return chunk.render(bodies.block, context);
} else {
return chunk.render(bodies['else'], context);
}
}
}
bodies.block
is a special parameter that returns the default (unnamed) block. chunk.render
renders the chosen block.
Accessing Inline Parameters
The params
object contains any inline parameters passed to a section tag:
{
hello: function(chunk, context, bodies, params) {
if (params.greet === "true") {
return chunk.write("Hello!");
}
return chunk;
}
}
Asynchronous Handlers
You may define handlers that execute asynchronously and in parallel:
{
type: function(chunk) {
return chunk.map(function(chunk) {
setTimeout(function() {
chunk.end("Async");
});
});
}
}
chunk.map
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 chunk.end()
on a mapped chunk to weave its content back into the stream.
chunk.map
provides a convenient way to split up templates rendered via dust.stream
. For example, you might wrap the head of an HTML document in a special {#head} ... {/head}
tag that is flushed to the browser before the rest of the body has finished rendering.
Reference
Compiling
dust.compile(source, name)
Compiles source
into a JavaScript template string. Registers itself under name
when evaluated.
dust.compileFn(source, [name])
Compiles source
directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource
). Registers the template under name
if this argument is supplied.
dust.optimizers
Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression:
dust.optimizers.format = function(ctx, node) { return node };
Loading
dust.register(name, fn)
Used internally to register template function fn
with the runtime environment. Override to customize the way Dust caches templates.
dust.onLoad(name, callback(err, out))
By default Dust returns a "template not found" error when a named template cannot be located in the cache. Override onLoad
to specify a fallback loading mechanism (e.g., to load templates from the filesystem or a database).
dust.loadSource(source, [filename])
Evaluates compiled source
string. In Node.js, evaluates source
as if it were loaded from filename
. filename
is optional.
Rendering
dust.render(name, context, callback(error, output))
Renders the named template and calls callback
on completion. context
may be a plain object or an instance of dust.Context
.
dust.stream(name, context)
Streams the named template. context
may be a plain object or an instance of dust.Context
. Returns an instance of dust.Stream
.
stream.on("data", listener(data))
stream.on("end", listener)
stream.on("error", listener(error))
Registers an event listener. Streams accept a single listener for a given event.
dust.renderSource(source, context, [callback(error, output)])
Compiles and renders source
, invoking callback
on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required.
Contexts
dust.makeBase(object)
Manufactures a dust.Context
instance with its global object set to object
.
context.get(key)
Retrieves the value at key
from the context stack.
context.push(head, [index], [length])
Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index
and/or length
to enable enumeration helpers.
context.rebase(head)
Returns a new context instance consisting only of the value at head
, plus any previously defined global object.
context.current()
Returns the head
of the context stack.
Chunks
The operations below always return a chunk object.
chunk.write(data)
Writes data
to this chunk's buffer.
chunk.map(callback(chunk))
Creates a new chunk and passes it to callback
. Use map
to wrap asynchronous functions and to partition the template for streaming.
chunk.end(data)
Writes data
to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map
. Do not call this method on a handler's main chunk -- dust.render
and dust.stream
take care of this for you.
chunk.tap(callback)
chunk.untap()
Convenience methods for applying filters to a stream. See the filter demo for an example.
chunk.render(body, context)
Renders a template block, such as a default block or an else
block. Basically equivalent to body(chunk, context)
.
chunk.setError(error)
Sets an error on this chunk and immediately flushes the output.
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)
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.
Utilities
dust.filters
Object containing built-in key filters. Can be customized with additional filters.
dust.helpers
Object containing the built-in context helpers. These may also be customized.
dust.escapeHtml
HTML escape function used by dust.filters.h
.
dust.escapeJs
JavaScript string escape function used by dust.filters.j
.