Browse files

initial commit

  • Loading branch information...
0 parents commit 170b3e22f1710286a1a534a9687ff9fb28c900c1 akdubya committed Oct 25, 2010
1 .gitignore
@@ -0,0 +1 @@
+/nbproject
19 Makefile
@@ -0,0 +1,19 @@
+#
+# Run all tests
+#
+test:
+ node test/server.js
+
+#
+# Run the benchmarks
+#
+bench:
+ node benchmark/server.js
+
+#
+# Build the docs
+#
+docs:
+ node docs/build.js
+
+.PHONY: test docs bench
0 README.md
No changes.
163 benchmark/index.html
@@ -0,0 +1,163 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <title>shootout</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <style type="text/css">
+ body {
+ background-color: #eee;
+ font-family: Helvetica, Arial, sans-serif;
+ margin: 0 10%;
+ text-shadow: white 1px 1px 0px;
+ }
+
+ p {
+ color: #777;
+ }
+
+ #header p {
+ color: #555;
+ font-size: 1.1em;
+ font-weight: bold;
+ }
+
+ h1 {
+ font-size: 7em;
+ font-weight: bold;
+ color: #333;
+ margin-top: 0.10em;
+ margin-bottom: -0.25em;
+ }
+
+ .chart {
+ border: 4px solid #ccc;
+ float: left;
+ margin-right: 1em;
+ margin-bottom: 1em;
+ }
+
+ #control {
+ margin-bottom: 1em;
+ }
+
+ #progress {
+ -moz-border-radius: 4px;
+ -webkit-border-radius: 4px;
+ border: 1px solid #aaa;
+ padding: 2px;
+ }
+
+ #progress div {
+ -moz-border-radius: 4px;
+ -webkit-border-radius: 4px;
+ height: 25px;
+ width: 0%;
+ background-color: #888;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="header">
+ <h1>shootout</h1>
+ <p>Template benchmarks (ops per millisecond)</p>
+ </div>
+
+ <div id="control">
+ <div id="progress"><div></div></div>
+ <button id="run" style="display:none;">Run</button>
+ </div>
+
+ <div id="content">
+ <div id="charts"></div>
+ <p style="clear: both">Targets: <a href="http://akdubya.github.com/dustjs">Dust</a>, <a href="http://github.com/wycats/handlebars.js">Handlebars</a>, <a href="http://mustache.github.com/">Mustache</a>, <a href="http://api.jquery.com/tmpl/">jquery-tmpl</a>. Each benchmark runs once using an adaptive test cycles algorithm similar to the one found in <a href="http://github.com/broofa/jslitmus">jslitmus</a>.</p>
+ </div>
+
+ <script src="../vendor/jquery.min.js"></script>
+ <script src="uubench.js"></script>
+ <script src="../lib/parser.js"></script>
+ <script src="../lib/compiler.js"></script>
+ <script src="../lib/dust.js"></script>
+ <script src="suites/dust_suite.js"></script>
+ <script src="suites/mustache_suite.js"></script>
+ <script src="suites/handlebars_suite.js"></script>
+ <script src="suites/jquery_suite.js"></script>
+ <script src="http://github.com/wycats/handlebars.js/raw/master/lib/handlebars.js"></script>
+ <script src="http://github.com/janl/mustache.js/raw/master/mustache.js"</script>
+ <script src="http://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js"></script>
+ <script type="text/javascript" src="http://www.google.com/jsapi"></script>
+ <script type="text/javascript">
+ google.load('visualization', '1.0', {packages: ['imagechart']});
+ </script>
+
+ <script>
+ $(document).ready(function(){
+ var testQueue = [];
+ var $bar = $('#progress > div');
+ var tick;
+
+ function runAll() {
+ $bar.css('width', "0%");
+ $('#progress').show();
+ for (var key in dustBench.benches) { testQueue.push(key) }
+ tick = 100 / testQueue.length;
+ $('#charts').empty();
+ next();
+ }
+
+ function next() {
+ var test = testQueue.shift();
+ if (test) {
+ runSuite(test);
+ } else {
+ $('#progress').fadeOut(1000, function() {
+ $('#run').fadeIn();
+ });
+ }
+ }
+
+ function runSuite(type) {
+ var rows = [];
+ var suite = new uubench.Suite({
+ iterations: 1000,
+ result: function(name, stats) {
+ var opms = stats.iterations/stats.elapsed;
+ rows.push([name, opms]);
+ },
+ start: function() {
+ $('#charts').append("<div id=\"" + type + "\" class=\"chart\"></div>");
+ },
+ done: function() {
+ var pct = parseFloat($bar.css('width')) + tick;
+ drawBarChart(type, rows);
+ $('#progress > div').css('width', pct + "%");
+ next();
+ }
+ });
+ dustBench(suite, type, "dust");
+ handlebarsBench(suite, type, "handlebars");
+ mustacheBench(suite, type, "mustache");
+ jqueryBench(suite, type, "jquery");
+ suite.run();
+ }
+
+ function drawBarChart(type, rows) {
+ var dataTable = new google.visualization.DataTable();
+ dataTable.addColumn("string", "engine");
+ dataTable.addColumn("number", "ops");
+ dataTable.addRows(rows);
+
+ var chart = new google.visualization.ImageChart(document.getElementById(type));
+ chart.draw(dataTable, {title: type, cht: 'bhs', chs: '420x175'});
+ }
+
+ $('#run').click(function() {
+ $('#run').hide();
+ runAll();
+ return false;
+ });
+
+ runAll();
+ });
+ </script>
+ </body>
+</html>
31 benchmark/server.js
@@ -0,0 +1,31 @@
+var uubench = require('./uubench'),
+ dust = require('../lib/dust'),
+ dustBench = require('./suites/dust_suite').dustBench;
+
+uubench.nextTick = process.nextTick;
+
+var suite = new uubench.Suite({
+ iterations: 10000,
+ result: function(name, stats) {
+ var opms = stats.iterations/stats.elapsed;
+ console.log(pad(12, name + ": "), pad(5, Math.round(opms), true));
+ }
+});
+
+function pad(amt, val, pre) {
+ val = String(val);
+ var len = amt - val.length, out = '';
+ for (var i=0; i<len; i++) {
+ out += ' ';
+ }
+ return pre ? out + val : val + out;
+}
+
+console.log("ops/ms");
+console.log("------");
+
+for (var key in dustBench.benches) {
+ dustBench(suite, key);
+}
+
+suite.run();
111 benchmark/suites/dust_suite.js
@@ -0,0 +1,111 @@
+(function(exports){
+
+var benches = {
+
+ string: {
+ source: "Hello World!",
+ context: {}
+ },
+
+ replace: {
+ source: "Hello {name}! You have {count} new messages.",
+ context: { name: "Mick", count: 30 }
+ },
+
+ array: {
+ source: "{#names}{name}{/names}",
+ context: { names: [
+ { name: "Moe" },
+ { name: "Larry" },
+ { name: "Curly" },
+ { name: "Shemp" }
+ ]
+ }
+ },
+
+ object: {
+ source: "{#person}{name}{age}{/person}",
+ context: { person: { name: "Larry", age: 45 } }
+ },
+
+ partial: {
+ source: "{#peeps}{>replace/}{/peeps}",
+ context: { peeps: [
+ { name: "Moe", count: 15 },
+ { name: "Larry", count: 5 },
+ { name: "Curly", count: 0 }
+ ]
+ }
+ },
+
+ recursion: {
+ source: "{name}{#kids}{>recursion:./}{/kids}",
+ context: {
+ name: '1',
+ kids: [
+ {
+ name: '1.1',
+ kids: [
+ {name: '1.1.1'}
+ ]
+ }
+ ]
+ }
+ },
+
+ filter: {
+ source: "{#filter}foo {bar}{/filter}",
+ context: {
+ filter: function(chunk, context, bodies) {
+ return chunk.tap(function(data) {
+ return data.toUpperCase();
+ }).render(bodies.block, context).untap();
+ },
+ bar: "bar"
+ }
+ },
+
+ complex: {
+ source: "<h1>{header}</h1>\n" +
+ "{?items}\n" +
+ " <ul>\n" +
+ " {#items}\n" +
+ " {#current}\n" +
+ " <li><strong>{name}</strong></li>\n" +
+ " {:else}\n" +
+ " <li><a href=\"{url}\">{name}</a></li>\n" +
+ " {/current}\n" +
+ " {/items}\n" +
+ " </ul>\n" +
+ "{:else}\n" +
+ " <p>The list is empty.</p>\n" +
+ "{/items}",
+ context: {
+ header: function() {
+ return "Colors";
+ },
+ items: [
+ {name: "red", current: true, url: "#Red"},
+ {name: "green", current: false, url: "#Green"},
+ {name: "blue", current: false, url: "#Blue"}
+ ]
+ }
+ }
+
+}
+
+exports.dustBench = function(suite, name, id) {
+ var bench = benches[name],
+ ctx = bench.context;
+
+ dust.loadSource(dust.compile(bench.source, name));
+ suite.bench(id || name, function(next) {
+ dust.render(name, ctx, function() {
+ next();
+ });
+ });
+};
+
+exports.dustBench.benches = benches;
+
+})(typeof exports !== "undefined" ? exports : window);
101 benchmark/suites/handlebars_suite.js
@@ -0,0 +1,101 @@
+(function(exports){
+
+var benches = {
+
+ string: {
+ source: "Hello World!",
+ context: {}
+ },
+
+ replace: {
+ source: "Hello {{name}}! You have {{count}} new messages.",
+ context: { name: "Mick", count: 30 }
+ },
+
+ array: {
+ source: "{{#names}}{{name}}{{/names}}",
+ context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
+ },
+
+ object: {
+ source: "{{#person}}{{name}}{{age}}{{/person}}",
+ context: { person: { name: "Larry", age: 45 } }
+ },
+
+ partial: {
+ source: "{{#peeps}}{{>replace}}{{/peeps}}",
+ context: { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] },
+ partials: { replace: "Hello {{name}}! You have {{count}} new messages." }
+ },
+
+ recursion: {
+ source: "{{name}}{{#kids}}{{>recursion}}{{/kids}}",
+ context: {
+ name: '1',
+ kids: [
+ {
+ name: '1.1',
+ kids: [
+ {name: '1.1.1'}
+ ]
+ }
+ ]
+ },
+ partials: { recursion: "{{name}}{{#kids}}{{>recursion}}{{/kids}}" }
+ },
+
+ filter: {
+ source: "{{#filter}}foo {{bar}}{{/filter}}",
+ context: {
+ filter: function(ctx, fn) {
+ return fn(ctx).toUpperCase();
+ },
+ bar: "bar"
+ }
+ },
+
+ complex: {
+ source: "<h1>{{header}}</h1>{{#hasItems}}<ul>{{#items}}{{#current}}" +
+ "<li><strong>{{name}}</strong></li>{{/current}}{{^current}}" +
+ "<li><a href=\"{{url}}\">{{name}}</a></li>{{/current}}" +
+ "{{/items}}</ul>{{^}}<p>The list is empty.</p>{{/hasItems}}",
+ context: {
+ header: function() {
+ return "Colors";
+ },
+ items: [
+ {name: "red", current: true, url: "#Red"},
+ {name: "green", current: false, url: "#Green"},
+ {name: "blue", current: false, url: "#Blue"}
+ ],
+ hasItems: function(ctx, fn) {
+ if (ctx.items.length) {
+ return fn(ctx);
+ }
+ }
+ }
+ }
+
+}
+
+exports.handlebarsBench = function(suite, name, id) {
+ var bench = benches[name],
+ fn = Handlebars.compile(bench.source),
+ ctx = bench.context,
+ partials = {};
+
+ if (bench.partials) {
+ for (var key in bench.partials) {
+ partials[key] = Handlebars.compile(bench.partials[key]);
+ }
+ }
+
+ suite.bench(id || name, function(next) {
+ fn(ctx, {partials: partials});
+ next();
+ });
+}
+
+exports.handlebarsBench.benches = benches;
+
+})(typeof exports !== "undefined" ? exports : window);
84 benchmark/suites/jquery_suite.js
@@ -0,0 +1,84 @@
+(function(exports){
+
+var benches = {
+
+ string: {
+ source: "Hello World!",
+ context: {}
+ },
+
+ replace: {
+ source: "Hello ${name}! You have ${count} new messages.",
+ context: { name: "Mick", count: 30 }
+ },
+
+ array: {
+ source: "{{each names}}${name}{{/each}}",
+ context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
+ },
+
+ object: {
+ source: "${person.name}${person.age}",
+ context: { person: { name: "Larry", age: 45 } }
+ },
+
+ partial: {
+ source: "{{tmpl(peeps) \"replace\"}}",
+ context: { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] }
+ },
+
+ recursion: {
+ source: "${name}{{tmpl(kids) \"recursion\"}}",
+ context: {
+ name: '1',
+ kids: [
+ {
+ name: '1.1',
+ kids: [
+ {name: '1.1.1', kids: []}
+ ]
+ }
+ ]
+ }
+ },
+
+ filter: {
+ source: "FOO ${bar.toUpperCase()}",
+ context: {
+ bar: "bar"
+ }
+ },
+
+ complex: {
+ source: "<h1>${header}</h1>{{if items.length}}<ul>{{each items}}{{if current}}" +
+ "<li><strong>${name}</strong></li>{{else}}" +
+ "<li><a href=\"${url}\">${name}</a></li>{{/if}}" +
+ "{{/each}}</ul>{{else}}<p>The list is empty.</p>{{/if}}",
+ context: {
+ header: function() {
+ return "Colors";
+ },
+ items: [
+ {name: "red", current: true, url: "#Red"},
+ {name: "green", current: false, url: "#Green"},
+ {name: "blue", current: false, url: "#Blue"}
+ ]
+ }
+ }
+
+}
+
+exports.jqueryBench = function(suite, name, id) {
+ var bench = benches[name],
+ fn = $.template(name, bench.source),
+ ctx = bench.context;
+
+ suite.bench(id || name, function(next) {
+ $.tmpl(fn, ctx);
+ next();
+ });
+}
+
+exports.jqueryBench.benches = benches;
+
+})(typeof exports !== "undefined" ? exports : window);
97 benchmark/suites/mustache_suite.js
@@ -0,0 +1,97 @@
+(function(exports){
+
+var benches = {
+
+ string: {
+ source: "Hello World!",
+ context: {}
+ },
+
+ replace: {
+ source: "Hello {{name}}! You have {{count}} new messages.",
+ context: { name: "Mick", count: 30 }
+ },
+
+ array: {
+ source: "{{#names}}{{name}}{{/names}}",
+ context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }
+ },
+
+ object: {
+ source: "{{#person}}{{name}}{{age}}{{/person}}",
+ context: { person: { name: "Larry", age: 45 } }
+ },
+
+ partial: {
+ source: "{{#peeps}}{{>replace}}{{/peeps}}",
+ context: { peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 1}] },
+ partials: { replace: "Hello {{name}}! You have {{count}} new messages." }
+ },
+
+ recursion: {
+ source: "{{name}}{{#kids}}{{>recursion}}{{/kids}}",
+ context: {
+ name: '1',
+ kids: [
+ {
+ name: '1.1',
+ kids: [
+ {name: '1.1.1', kids: []}
+ ]
+ }
+ ]
+ },
+ partials: { recursion: "{{name}}{{#kids}}{{>recursion}}{{/kids}}" }
+ },
+
+ filter: {
+ source: "{{#filter}}foo {{bar}}{{/filter}}",
+ context: {
+ filter: function() {
+ return function(text, render) {
+ return render(text).toUpperCase();
+ }
+ },
+ bar: "bar"
+ }
+ },
+
+ complex: {
+ source: "<h1>{{header}}</h1>{{#hasItems}}<ul>{{#items}}{{#current}}" +
+ "<li><strong>{{name}}</strong></li>{{/current}}{{^current}}" +
+ "<li><a href=\"{{url}}\">{{name}}</a></li>{{/current}}" +
+ "{{/items}}</ul>{{/hasItems}}{{^hasItems}}<p>The list is empty.</p>{{/hasItems}}",
+ context: {
+ header: function() {
+ return "Colors";
+ },
+ items: [
+ {name: "red", current: true, url: "#Red"},
+ {name: "green", current: false, url: "#Green"},
+ {name: "blue", current: false, url: "#Blue"}
+ ],
+ hasItems: function() {
+ return this.items.length !== 0;
+ },
+ empty: function() {
+ return this.items.length === 0;
+ }
+ }
+ }
+}
+
+exports.mustacheBench = function(suite, name, id) {
+ var bench = benches[name],
+ src = bench.source,
+ ctx = bench.context,
+ partials = bench.partials;
+
+ suite.bench(id || name, function(next) {
+ Mustache.to_html(src, ctx, partials);
+ next();
+ });
+}
+
+exports.mustacheBench.benches = benches;
+
+})(typeof exports !== "undefined" ? exports : window);
107 benchmark/uubench.js
@@ -0,0 +1,107 @@
+(function(uubench){
+
+function Bench(id, test, options, callback) {
+ this.id = id;
+ this.options = options;
+ this.test = test;
+ this.loop = test.length > 1;
+ this.callback = callback;
+}
+
+Bench.prototype.run = function(iter) {
+ var self = this, fn = self.test,
+ checkfn = self.options.type === "adaptive" ? adaptive : fixed,
+ i = iter, pend = i,
+ min = self.options.min, start;
+
+ if (self.loop) {
+ pend = 1;
+ start = new Date();
+ fn(checkfn, i);
+ } else {
+ start = new Date();
+ while (i--) {
+ fn(checkfn);
+ }
+ }
+
+ function fixed() {
+ if (--pend === 0) {
+ var elapsed = new Date() - start;
+ self.callback({iterations: iter, elapsed: elapsed});
+ }
+ }
+
+ function adaptive() {
+ if (--pend === 0) {
+ var elapsed = new Date() - start;
+ if (elapsed < min) {
+ self.run(iter*2);
+ } else {
+ self.callback({iterations: iter, elapsed: elapsed});
+ }
+ }
+ }
+}
+
+uubench.Bench = Bench;
+
+uubench.defaults = {
+ type: "adaptive", // adaptive or fixed
+ iterations: 10, // starting iterations
+ min: 100, // minimum run time (ms) - adaptive only
+ delay: 100 // delay between tests (ms)
+}
+
+function Suite(opts) {
+ for (var key in uubench.defaults) {
+ if (opts[key] === undefined) {
+ opts[key] = uubench.defaults[key];
+ }
+ }
+ this.options = opts;
+ this.tests = [];
+}
+
+Suite.prototype.bench = function(name, fn) {
+ var self = this;
+ self.tests.push(new Bench(name, fn, this.options, function(stats) {
+ self.emit("result", name, stats);
+ self.pending--;
+ self.check();
+ }));
+}
+
+Suite.prototype.run = function() {
+ if (this.pending) return;
+ var self = this, len = self.tests.length;
+ self.emit("start", self.tests);
+ self.start = new Date().getTime();
+ self.pending = len;
+ for (var i=0; i<len; i++) {
+ self.runOne(i);
+ }
+}
+
+Suite.prototype.runOne = function(idx) {
+ var self = this;
+ setTimeout(function() {
+ self.tests[idx].run(self.options.iterations);
+ }, self.options.delay);
+}
+
+Suite.prototype.check = function() {
+ if (this.pending) return;
+ this.emit("done", new Date().getTime() - this.start);
+}
+
+Suite.prototype.emit = function(type) {
+ var event = this.options[type];
+ if (event) {
+ event.apply(this, Array.prototype.slice.call(arguments, 1));
+ }
+}
+
+uubench.Suite = Suite;
+
+})(typeof exports !== 'undefined' ? exports : window.uubench = {});
14 docs/about.md
@@ -0,0 +1,14 @@
+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:
+
++ __Markup-like__: _A templating syntax should not encompass operations that are better left to a programming language_. Templates should make it easy to format content for presentation while keeping application logic where it belongs: in the application.
++ __Asynchronous__: Template helpers should be callable _asynchronously_ and in _parallel_ so that expensive operations (caching, deferred loading, filtering) can run as the template is being rendered.
++ __Streaming__: Templates should allow (but not require) data to be flushed to the output in user-defined chunks.
++ __Browser and server compatible__: Templates should render in both server and browser environments without hacks or extensive configuration.
++ __Storage agnostic__: _The templating engine should not impose a particular loading scheme_. Developers should be free to load templates via the filesystem, a database or an army of carrier pigeons.
++ __Composable__: Designers should be able to break presentation markup into manageable components and combine these components at runtime. _It should not be necessary to statically link templates or manually assemble 'layouts' inside application code._
++ __Format agnostic__: 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.
++ __Precise__: 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.
++ __Safe(r)__: At the very least, the engine should be configurable such that it is reasonably safe to render untrusted templates in a server environment.
++ __Fast__: Server-side templates cannot always be cached. Browser-side templates may be rendered on devices with limited system resources. _A template engine should be fast enough to render in real time without bottlenecking its environment_.
+
+If this list leaves you nodding your head in agreement you should [give Dust a try](http://akdubya.github.com/dustjs).
291 docs/api.md
@@ -0,0 +1,291 @@
+A pure JavaScript library, Dust is runs in both browser-side and server-side environments. Dust templates are precompiled and then loaded where they are needed along with the `dust.js` 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, clone the repository and require `dust.js`:
+
+ var dust = require("path/to/dust/lib/dust");
+
+This will import everything needed to parse, compile and render templates.
+
+To render Dust templates in the browser, include the `dust.js` runtime in your script tags, along with your precompiled templates. You may run the parser and compiler within the browser if you like (as in the online demo), but precompilation is a much cleaner approach.
+
+### 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.Context.base({
+ 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.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, function)
+
+Used internally to register templates with the runtime environment. Override to customize the way Dust caches templates.
+
+ dust.load(name, chunk, context)
+
+Used internally to loads and render the named template. Override to change the way templates are loaded (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.
+
+#### Contexts
+
+ dust.Context.base(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(function)
+ 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`.
68 docs/build.js
@@ -0,0 +1,68 @@
+var path = require('path'),
+ fs = require('fs'),
+ Script = process.binding('evals').Script,
+ dust = require('../lib/dust'),
+ root = path.join(path.dirname(__filename), "..");
+
+var src = fs.readFileSync(path.join(root, 'docs/index.dust.html'), 'utf8');
+dust.loadSource(dust.compile(src, "index"));
+
+var sd = process.compile(fs.readFileSync(path.join(root, 'vendor/showdown.js'), 'utf8'), 'showdown.js');
+
+var inliners = {
+ css: function(names) {
+ var out = "<style type=\"text/css\">";
+ names.forEach(function(name) {
+ out += fs.readFileSync(path.join(root, 'docs', name + '.css'), 'utf8');
+ });
+ out += "</style>";
+ return out;
+ },
+
+ js: function(names) {
+ var out = "<script type=\"text/javascript\">";
+ names.forEach(function(name) {
+ out += fs.readFileSync(path.join(root, 'docs', name + '.js'), 'utf8');
+ });
+ out += "</script>";
+ return out;
+ }
+}
+
+var context = {
+ inline: function(chk, ctx, bod, prm) {
+ var names = prm.names.split(' ');
+ return chk.write(inliners[prm.ext](names));
+ },
+
+ tmpl: function(chk, ctx, bod, prm) {
+ var names = prm.names.split(' ');
+ var out = "<script type=\"text/javascript\">";
+ names.forEach(function(name) {
+ out += dust.compile(fs.readFileSync(path.join(root, 'docs', name + '.dust.html'), 'utf8'), "select");
+ });
+ out += "</script>";
+ return chk.write(out);
+ },
+
+ md: function(chk, ctx, bod, prm) {
+ var converter = new sd();
+ return chk.tap(function(data) {
+ return converter.makeHtml(data);
+ }).render(bod.block, ctx).untap();
+ },
+
+ file: function(chk, ctx, bod, prm) {
+ var name = prm.name;
+ return chk.write(fs.readFileSync(path.join(root, 'docs', name), 'utf8'));
+ }
+}
+
+function render() {
+ dust.render("index", context, function(err, output) {
+ if (err) throw err;
+ fs.writeFileSync(path.join(root, 'index.html'), output);
+ });
+}
+
+render();
202 docs/index.css
@@ -0,0 +1,202 @@
+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 {
+ font-size: 32px;
+ font-weight: normal;
+ margin: 12px 0 12px 2%;
+}
+
+h1 {
+ float: left;
+}
+
+h3 {
+ font-size: 24px;
+}
+
+h4 {
+ font-size: 1em;
+}
+
+h1, h2, pre, code, .console, .status, #nav, #tagline {
+ font-family: '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;
+}
+
+#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 {
+ float: left;
+ margin-left: 10px;
+ margin-top: 24px;
+ font-size: 14px;
+}
+
+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%;
+}
+
+textarea {
+ width: 100%;
+ display: block;
+ margin-top: 26px;
+ margin-bottom: 26px;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+}
+
+.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 }
93 docs/index.dust.html
@@ -0,0 +1,93 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <title>dust</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ {#inline names="index" ext="css"/}
+ <script src="vendor/jquery.min.js"></script>
+ <script src="vendor/jsdump.js"></script>
+ <script src="vendor/beautify.js"></script>
+ <script src="lib/parser.js"></script>
+ <script src="lib/compiler.js"></script>
+ <script src="lib/dust.js"></script>
+ <script src="test/examples.js"></script>
+ <script src="test/uutest.js"></script>
+ <script src="test/core.js"></script>
+ {#tmpl names="select"/}
+ {#inline names="index" ext="js"/}
+ </head>
+ <body>
+ <div id="dust" class="content">
+ <div class="left">
+ <div class="header">
+ <h1>{~lb}dust{~rb}</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>
+ <textarea id="output-js" class="console"></textarea>
+ <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>
+ <textarea id="output-text" class="console"></textarea>
+ </div>
+ </div>
+ </div>
+ <div id="guide" class="content">
+ <div class="left">
+ <div class="header">
+ <h2>{~lb}guide{~rb}</h2>
+ </div>
+ <div id="syntax" class="col1">
+ {#md}{#file name="syntax.md"/}{/md}
+ </div>
+ <div id="api" class="col2">
+ {#md}{#file name="api.md"/}{/md}
+ </div>
+ </div>
+ </div>
+ <div id="tests" class="content">
+ <div class="left">
+ <div class="header">
+ <h2>{~lb}tests{~rb}</h2>
+ </div>
+ <div class="col1">
+ <p>If the console below indicates an error then we have a problem.</p>
+ <textarea id="test-console" class="console"></textarea>
+ </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>{~lb}about{~rb}</h2>
+ </div>
+ <div class="col1">
+ {#md}{#file name="about.md"/}{/md}
+ </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>
187 docs/index.js
@@ -0,0 +1,187 @@
+dustExamples.forEach(function(ex) {
+ dust.loadSource(dust.compile(ex.source, ex.name));
+});
+
+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) {
+ jsDump.parsers['function'] = function(fn) {
+ return fn.toString();
+ }
+ return js_beautify(jsDump.parse(obj), {
+ indent_size: 2
+ });
+}
+
+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;
+}
+
+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));
+ suite.run();
+}
+
+$(document).ready(function(){
+ runSuite();
+
+ $('#tagline').empty();
+ dust.loadSource(dust.compile(dustExamples[0].source, "intro"));
+ dust.stream("intro", dustExamples[0].context()).on('data', function(data) {
+ $('#tagline').append(data);
+ });
+
+ 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();
+ });
+
+ $(".cwrap > h3 > span").click(function() {
+ var $console = $(this).closest(".cwrap").children(".console"),
+ $anchor = $(this).children("a");
+
+ if ($console.is(":visible")) {
+ $console.hide();
+ $anchor.html("show");
+ } else {
+ $console.show();
+ $anchor.html("hide");
+ }
+ return false;
+ });
+
+ $('#input-source').change(function() {
+ setPending('#input-source');
+ try {
+ var compiled = dust.compile($(this).val(), "demo");
+ dust.loadSource(compiled);
+ $('#output-js').val(js_beautify(compiled, {
+ indent_size: 2
+ }));
+ setOkay('#input-source');
+ } catch(err) {
+ setError('#input-source', err);
+ return;
+ }
+ renderDemo();
+ });
+
+ $('#input-context').change(renderDemo);
+
+ $('#select > select').change();
+
+ 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 foof = $(section).find('.header').clone();
+ if (section.id !== cur_id) {
+ cur_id = section.id;
+ $('.docked').remove();
+ foof.appendTo('body');
+ foof.addClass('docked');
+ }
+ return false;
+ }
+ });
+ });
+});
5 docs/select.dust.html
@@ -0,0 +1,5 @@
+<select style="clear: both;">
+ {#examples}
+ <option {selected} value="{@idx}{.}{/idx}">{name}</option>
+ {/examples}
+</select>
286 docs/syntax.md
@@ -0,0 +1,286 @@
+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:
+
+ &lt;script&gt;alert('I am evil!')&lt;/script&gt;
+
+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
1,059 index.html
@@ -0,0 +1,1059 @@
+<!DOCTYPE HTML><html><head><title>dust</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><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 {
+ font-size: 32px;
+ font-weight: normal;
+ margin: 12px 0 12px 2%;
+}
+
+h1 {
+ float: left;
+}
+
+h3 {
+ font-size: 24px;
+}
+
+h4 {
+ font-size: 1em;
+}
+
+h1, h2, pre, code, .console, .status, #nav, #tagline {
+ font-family: '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;
+}
+
+#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 {
+ float: left;
+ margin-left: 10px;
+ margin-top: 24px;
+ font-size: 14px;
+}
+
+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%;
+}
+
+textarea {
+ width: 100%;
+ display: block;
+ margin-top: 26px;
+ margin-bottom: 26px;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+}
+
+.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/jquery.min.js"></script><script src="vendor/jsdump.js"></script><script src="vendor/beautify.js"></script><script src="lib/parser.js"></script><script src="lib/compiler.js"></script><script src="lib/dust.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);var blocks=null;function body_2(chk,ctx){return chk.reference(ctx.getPath(true,[]),ctx,"h",[]);}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_0(chk,ctx){ctx=ctx.shiftBlocks(blocks);return chk.write("<select style=\"clear: both;\">").section(ctx.get("examples"),ctx,{"block":body_1},null).write("</select>");}})();</script><script type="text/javascript">dustExamples.forEach(function(ex) {
+ dust.loadSource(dust.compile(ex.source, ex.name));
+});
+
+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) {
+ jsDump.parsers['function'] = function(fn) {
+ return fn.toString();
+ }
+ return js_beautify(jsDump.parse(obj), {
+ indent_size: 2
+ });
+}
+
+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;
+}
+
+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));
+ suite.run();
+}
+
+$(document).ready(function(){
+ runSuite();
+
+ $('#tagline').empty();
+ dust.loadSource(dust.compile(dustExamples[0].source, "intro"));
+ dust.stream("intro", dustExamples[0].context()).on('data', function(data) {
+ $('#tagline').append(data);
+ });
+
+ 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();
+ });
+
+ $(".cwrap > h3 > span").click(function() {
+ var $console = $(this).closest(".cwrap").children(".console"),
+ $anchor = $(this).children("a");
+
+ if ($console.is(":visible")) {
+ $console.hide();
+ $anchor.html("show");
+ } else {
+ $console.show();
+ $anchor.html("hide");
+ }
+ return false;
+ });
+
+ $('#input-source').change(function() {
+ setPending('#input-source');
+ try {
+ var compiled = dust.compile($(this).val(), "demo");
+ dust.loadSource(compiled);
+ $('#output-js').val(js_beautify(compiled, {
+ indent_size: 2
+ }));
+ setOkay('#input-source');
+ } catch(err) {
+ setError('#input-source', err);
+ return;
+ }
+ renderDemo();
+ });
+
+ $('#input-context').change(renderDemo);
+
+ $('#select > select').change();
+
+ 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 foof = $(section).find('.header').clone();
+ if (section.id !== cur_id) {
+ cur_id = section.id;
+ $('.docked').remove();
+ foof.appendTo('body');
+ foof.addClass('docked');
+ }
+ return false;
+ }
+ });
+ });
+});</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><textarea id="output-js" class="console"></textarea><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><textarea id="output-text" class="console"></textarea></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>