818
Du
dustymarkdown / files
dustymarkdown / node_modules / dust / index.html
38.1 KB
1<!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 { 2 font-family: 'Georgia', serif; 3 font-size: 18px; 4 margin: 0; 5 padding: 0; 6} 7 8p, h4, h3, .content ul { 9 line-height: 26px; 10 margin-top: 26px; 11 margin-bottom: 26px; 12} 13 14.content ul li { 15 margin-top: 13px; 16 margin-bottom: 13px; 17} 18 19h1, h2 { 20 line-height: 48px; 21 font-size: 32px; 22 font-weight: normal; 23 margin: 8px 0 8px 2%; 24} 25 26h3 { 27 font-size: 24px; 28} 29 30h4 { 31 font-size: 1em; 32} 33 34h1, h2, pre, code, .console, .status, #nav, #tagline { 35 font-family: 'Droid Sans Mono', 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace; 36} 37 38a:link, a:visited { 39 color: #ef674a; 40} 41 42p code { 43 font-size: 16px; 44 line-height: 16px; 45} 46 47pre, .console { 48 background-color: #191919; 49 white-space: pre-wrap; 50 word-wrap: break-word; 51} 52 53.console { 54 font-size: 16px; 55 height: 270px; 56 color: #dddddd; 57 margin-top: 26px; 58 margin-bottom: 26px; 59 border: 1px solid #888; 60 resize: auto; 61 overflow: auto; 62 padding: 2px; 63} 64 65textarea { 66 width: 100%; 67 display: block; 68 -moz-box-sizing: border-box; 69 -webkit-box-sizing: border-box; 70} 71 72#nav { 73 position: fixed; 74 top: 18px; 75 right: 2%; 76 font-size: 22px; 77 z-index: 99; 78} 79 80#nav a:link, #nav a:visited { 81 color: #eaf2d9; 82} 83 84#nav a { 85 text-decoration: none; 86 margin-left: 17px; 87} 88 89#nav a:last { 90 margin: 0; 91} 92 93#tagline { 94 position: absolute; 95 display: none; 96 top: 24px; 97 font-size: 14px; 98} 99 100#guide pre { 101 font-size: 16px; 102 line-height: 26px; 103 color: #dddddd; 104 padding: 26px; 105 margin: 26px 0; 106} 107 108#header, #demo { 109 clear: both; 110} 111 112.ok { 113 background-color: green; 114} 115 116.error { 117 background-color: red; 118} 119 120.pending { 121 background-color: yellow; 122} 123 124.status { 125 font-size: 14px; 126 padding: 2px; 127 margin-top: -24px; 128} 129 130.header, .content { 131 clear: both; 132 width: 100%; 133 overflow: hidden; 134 color: #ede6da; 135} 136 137.header { 138 clear: both; 139 width: 100%; 140 -webkit-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4); 141 -moz-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4); 142 background-color: #581406; 143} 144 145.content { 146 background-color: #2d2929; 147} 148 149.left { 150 float: left; 151 width: 100%; 152 position: relative; 153 -webkit-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4); 154 -moz-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4); 155} 156 157.content .left, .header .left { 158 right: 50%; 159} 160 161.content .left { 162 background-color: #272121; 163} 164 165.header, .col1, .col2 { 166 float: left; 167 position: relative; 168 overflow: hidden; 169} 170 171.col1 { 172 width: 96%; 173 left: 2%; 174} 175 176.left .header { 177 width: 100%; 178 left: 50%; 179} 180 181.left .col1 { 182 width: 46%; 183 left: 52%; 184} 185 186.left .col2 { 187 width: 46%; 188 left: 56%; 189} 190 191.docked { 192 position: fixed; 193 width: 100%; 194 top: 0; 195 background-color: hsla(10, 87%, 18%, 0.80); 196 z-index: 5; 197} 198 199code .keyword { font-weight: bold; color: #dd7522 } 200code .string, code .regexp { color: #669933 } 201code .class, code .special { } 202code .number { color: #eddd3d } 203code .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) { 204 return fn.toString(); 205} 206 207function renderDemo() { 208 var tmpl = dust.cache["demo"], 209 source = $('#input-context').val(); 210 211 $('#output-text').empty(); 212 213 if (tmpl && source) { 214 setPending('#input-context'); 215 setPending('#output-text'); 216 try { 217 eval("var context = " + source + ";"); 218 if (typeof context === 'function') { 219 context = context(); 220 } 221 dust.stream("demo", context) 222 .on('data', function(data) { 223 $('#output-text').append(dust.escapeHtml(data)); 224 }) 225 .on('end', function() { 226 setOkay('#input-context'); 227 setOkay('#output-text'); 228 }) 229 .on('error', function(err) { 230 setError('#input-context', err); 231 }); 232 } catch(err) { 233 setError('#input-context', err); 234 } 235 } 236} 237 238function setOkay(sel) { 239 $(sel).next() 240 .removeClass('pending') 241 .addClass('ok') 242 .html('Ready'); 243} 244 245function setPending(sel) { 246 $(sel).next() 247 .removeClass('ok') 248 .removeClass('error') 249 .addClass('pending') 250 .html('Pending'); 251} 252 253function setError(sel, err) { 254 $(sel).next() 255 .removeClass('pending') 256 .addClass('error') 257 .html(err.toString()); 258} 259 260function dump(obj) { 261 return js_beautify(jsDump.parse(obj), { 262 indent_size: 2 263 }); 264} 265 266function runSuite() { 267 var suite = new uutest.Suite({ 268 start: function() { 269 $('#test-console').empty(); 270 }, 271 pass: function() { 272 $('#test-console').append("."); 273 }, 274 fail: function() { 275 $('#test-console').append("F"); 276 }, 277 done: function(passed, failed, elapsed) { 278 $('#test-console').append("\n"); 279 $('#test-console').append(passed + " passed " + failed + " failed " + "(" + elapsed + "ms)"); 280 this.errors.forEach(function(err) { 281 $('#test-console').append("\n"); 282 $('#test-console').append(dust.escapeHtml(dumpError(err))); 283 }); 284 } 285 }); 286 coreSetup(suite, dustExamples.slice(1), dust); 287 suite.run(); 288} 289 290function dumpError(err) { 291 var out = err.testName + " -> "; 292 if (!err.message) { 293 err.message = jsDump.parse(err.expected) 294 + " " + err.operator + " " + jsDump.parse(err.actual); 295 } 296 return out + err.stack; 297} 298 299$(document).ready(function() { 300 301 dustExamples.forEach(function(ex) { 302 dust.loadSource(dust.compile(ex.source, ex.name)); 303 }); 304 305 runSuite(); 306 307 $('#tagline').empty().show().css({left: ($(window).width() * .02) + 125}); 308 dust.loadSource(dust.compile(dustExamples[0].source, "intro")); 309 dust.stream("intro", dustExamples[0].context()) 310 .on('data', function(data) { 311 $('#tagline').append(data); 312 }) 313 .on('end', function() { 314 $('#tagline').delay(500).fadeOut('slow'); 315 }); 316 317 dust.render("select", { 318 examples: dustExamples, 319 selected: function(chk, ctx) { 320 if (ctx.current().name === "replace") return "selected"; 321 } 322 }, function(err, output) { 323 $('#select').html(output); 324 }); 325 326 $('#select > select').change(function() { 327 var idx = $(this).val(); 328 $('#input-source').val(dustExamples[idx].source); 329 $('#input-context').val(dump(dustExamples[idx].context)); 330 $('#input-source').change(); 331 }); 332 333 $('#input-source').change(function() { 334 setPending('#input-source'); 335 try { 336 var compiled = dust.compile($(this).val(), "demo"); 337 dust.loadSource(compiled); 338 $('#output-js').text(js_beautify(compiled, { 339 indent_size: 2 340 })); 341 setOkay('#input-source'); 342 } catch(err) { 343 setError('#input-source', err); 344 return; 345 } 346 renderDemo(); 347 }); 348 349 $('#input-context').change(renderDemo); 350 351 var sections = $("body > div"); 352 var cur_id; 353 354 $(window).scroll(function() { 355 var scrollTop = $(window).scrollTop(); 356 357 if (scrollTop === 0) { 358 cur_id = undefined; 359 $('.docked').remove(); 360 return; 361 } 362 363 sections.each(function(idx, section) { 364 var sectionTop = section.offsetTop, 365 sectionBottom = sectionTop + section.offsetHeight; 366 367 if (scrollTop >= sectionTop && scrollTop < sectionBottom) { 368 var $hdr = $(section).find('.header').clone(); 369 if (section.id !== cur_id) { 370 cur_id = section.id; 371 $('.docked').remove(); 372 $hdr.appendTo('body'); 373 $hdr.addClass('docked'); 374 } 375 return false; 376 } 377 }); 378 }); 379 380 $('#select > select').change(); 381 $(window).scroll(); 382 383});</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> 384 385<h3>Syntax</h3> 386 387<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> 388 389<h3>Keys</h3> 390 391<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> 392 393<pre><code>Hello {name}! 394</code></pre> 395 396<p>And the following view context:</p> 397 398<pre><code>{ name: "Fred" } 399</code></pre> 400 401<p>The resulting output would be:</p> 402 403<pre><code>Hello Fred! 404</code></pre> 405 406<p>If the <em>name</em> key cannot be found in the view, Dust outputs an empty string:</p> 407 408<pre><code>Hello ! 409</code></pre> 410 411<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> 412 413<h4>Filters</h4> 414 415<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> 416 417<pre><code><script>alert('I am evil!')</script> 418</code></pre> 419 420<p>This would be rendered as:</p> 421 422<pre><code>&lt;script&gt;alert('I am evil!')&lt;/script&gt; 423</code></pre> 424 425<p>To disable auto-escaping, append a pipe character '|' and an 's' to the end of the tag identifier, like so:</p> 426 427<pre><code>Hello {name|s} 428</code></pre> 429 430<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> 431 432<pre><code>Hello {name|s|h|u} 433</code></pre> 434 435<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> 436 437<h3>Sections</h3> 438 439<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> 440 441<pre><code>{#friends} 442 {name}, {age}{~n} 443{/friends} 444</code></pre> 445 446<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> 447 448<pre><code>{ 449 friends: [ 450 { name: "Moe", age: 37 }, 451 { name: "Larry", age: 39 }, 452 { name: "Curly", age: 35 } 453 ] 454} 455</code></pre> 456 457<p>The output is as one might expect:</p> 458 459<pre><code>Moe, 37 460Larry, 39 461Curly, 35 462</code></pre> 463 464<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> 465 466<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> 467 468<pre><code>{#friends} 469 {name}, {age}{~n} 470{:else} 471 You have no friends! 472{/friends} 473</code></pre> 474 475<p>Now when the friends key is empty or nonexistent we get the following:</p> 476 477<pre><code>You have no friends! 478</code></pre> 479 480<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> 481 482<p>Self-closing section tags are allowed, so the template code below is permissible (although in this case it won't render anything):</p> 483 484<pre><code>{#friends/} 485</code></pre> 486 487<h4>Paths</h4> 488 489<p>Paths allow you to reference keys relative to the current context. </p> 490 491<pre><code>{#names}{.} {/names} 492</code></pre> 493 494<p>The dot notation above lets the template reference the current context implicitly, so given an array of strings:</p> 495 496<pre><code>{ names: ["Moe", "Larry", "Curly"] } 497</code></pre> 498 499<p>The template block outputs each string in the array.</p> 500 501<pre><code>Moe Larry Curly 502</code></pre> 503 504<p>Paths can also be used to reach into nested contexts:</p> 505 506<pre><code>{foo.bar} 507</code></pre> 508 509<p>Or to constrain lookups to the current section scope:</p> 510 511<pre><code>{.foo} 512</code></pre> 513 514<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> 515 516<h4>Inline Parameters</h4> 517 518<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> 519 520<pre><code>{#profile bar="baz" bing="bong"} 521 {name}, {bar}, {bing} 522{/profile} 523</code></pre> 524 525<p>Assuming <em>name</em> within the profile section resolves to "Fred", the output would be:</p> 526 527<pre><code>Fred, baz, bong 528</code></pre> 529 530<p>Inline parameters may be used to alias keys that conflict between parent and child contexts:</p> 531 532<pre><code>{name}{~n} 533{#profile root_name=name} 534 {name}, {root_name} 535{/profile} 536</code></pre> 537 538<p>Note here that we're passing in a key rather than a string literal. If the context is as follows:</p> 539 540<pre><code>{ 541 name: "Foo", 542 profile: { 543 name: "Bar" 544 } 545} 546</code></pre> 547 548<p>The output will be:</p> 549 550<pre><code>Foo 551Bar, Foo 552</code></pre> 553 554<p>Parameters accept interpolated string literals as values:</p> 555 556<pre><code>{#snippet id="{name}_id"/} 557</code></pre> 558 559<h4>Body Parameters</h4> 560 561<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> 562 563<h4>Contexts</h4> 564 565<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> 566 567<pre><code>{#list:projects}{name}{/list} 568</code></pre> 569 570<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> 571 572<h4>Special Sections</h4> 573 574<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> 575 576<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> 577 578<pre><code>{?tags} 579 <ul> 580 {#tags} 581 <li>{.}</li> 582 {/tags} 583 </ul> 584{:else} 585 No Tags! 586{/tags} 587</code></pre> 588 589<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> 590 591<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> 592 593<pre><code>{#names}{.}{@idx}{.}{/idx}{@sep}, {/sep}{/names} 594</code></pre> 595 596<p>The template above might output something like:</p> 597 598<pre><code>Moe0, Larry1, Curly2 599</code></pre> 600 601<h3>Partials</h3> 602 603<p>Partials, also known as template includes, allow you to compose templates at runtime.</p> 604 605<pre><code>{>profile/} 606</code></pre> 607 608<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> 609 610<pre><code>{>profile:user/} 611</code></pre> 612 613<p>Partial tags also accept string literals and interpolated string literals as keys:</p> 614 615<pre><code>{>"path/to/comments.dust.html"/} 616{>"posts/{type}.dust.html"/} 617</code></pre> 618 619<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> 620 621<h3>Blocks and Inline Partials</h3> 622 623<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> 624 625<pre><code>Start{~n} 626{+title} 627 Base Title 628{/title} 629{~n} 630{+main} 631 Base Content 632{/main} 633{~n} 634End 635</code></pre> 636 637<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> 638 639<pre><code>Start 640Base Title 641Base Content 642End 643</code></pre> 644 645<p>But when the template is invoked from another template that contains inline partial tags (<code>{<snippet} ... {/snippet}</code>):</p> 646 647<pre><code>{>base_template/} 648{<title} 649 Child Title 650{/title} 651{<main} 652 Child Content 653{/main} 654</code></pre> 655 656<p>Dust overrides the block contents of the base template:</p> 657 658<pre><code>Start 659Child Title 660Child Content 661End 662</code></pre> 663 664<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> 665 666<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> 667 668<pre><code>{^xhr} 669 {>base_template/} 670{:else} 671 {+main/} 672{/xhr} 673{<title} 674 Child Title 675{/title} 676{<main} 677 Child Content 678{/main} 679</code></pre> 680 681<h3>Static Text</h3> 682 683<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> 684 685<h4>Special Characters</h4> 686 687<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> 688 689<pre><code>Hello World!{~n} 690</code></pre> 691 692<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> 693 694<h4>Comments</h4> 695 696<p>Comments, which do not appear in template output, begin and end with a bang (<code>!</code>):</p> 697 698<pre><code>{! 699 Multiline 700 {#foo}{bar}{/foo} 701!} 702{!before!}Hello{!after!} 703</code></pre> 704 705<p>The template above would render as follows:</p> 706 707<pre><code>Hello 708</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> 709 710<h3>Installation</h3> 711 712<p>To run Dust within Node.js, first install via <a href="http://github.com/isaacs/npm">npm</a>:</p> 713 714<pre><code>npm install dust 715</code></pre> 716 717<p>Then, within your Node script or the REPL:</p> 718 719<pre><code>var dust = require('dust'); 720</code></pre> 721 722<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> 723 724<pre><code><script src="dust-core-0.3.0.min.js"></script> 725<script src="compiled_templates.js"></script> 726</code></pre> 727 728<p>Include the full distribution if you want to compile templates within the browser (as in the online demo):</p> 729 730<pre><code><script src="dust-full-0.3.0.min.js"></script> 731</code></pre> 732 733<p>Precompilation is the recommended approach for general use.</p> 734 735<h3>Compiling Templates</h3> 736 737<p>Use <code>dust.compile</code> to compile a template body into a string of JavaScript source code:</p> 738 739<pre><code>var compiled = dust.compile("Hello {name}!", "intro"); 740</code></pre> 741 742<p>The variable <code>compiled</code> now contains the following string:</p> 743 744<pre><code>'(function(){dust.register("intro",body_0) ...' 745</code></pre> 746 747<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> 748 749<pre><code>dust.loadSource(compiled); 750</code></pre> 751 752<p>The template is now available within the <code>dust.cache</code> object.</p> 753 754<h3>Rendering Templates</h3> 755 756<p>The rendering engine provides both callback and streaming interfaces.</p> 757 758<h4>The Callback Interface</h4> 759 760<p>To render a template, call <code>dust.render</code> with the template name, a context object and a callback function:</p> 761 762<pre><code>dust.render("intro", {name: "Fred"}, function(err, out) { 763 console.log(out); 764}); 765</code></pre> 766 767<p>The code above will write the following to the console:</p> 768 769<pre><code>Hello Fred! 770</code></pre> 771 772<h4>The Streaming Interface</h4> 773 774<p>Templates may also be streamed. <code>dust.stream</code> returns a handler very similar to a Node <code>EventEmitter</code>:</p> 775 776<pre><code>dust.stream("index", context) 777 .on("data", function(data) { 778 console.log(data); 779 }) 780 .on("end", function() { 781 console.log("I'm finished!"); 782 }) 783 .on("error", function(err) { 784 console.log("Something terrible happened!"); 785 }); 786</code></pre> 787 788<p>When used with specially crafted context handlers, the streaming interface provides chunked template rendering.</p> 789 790<h3>Contexts</h3> 791 792<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> 793 794<pre><code>global --> { helper: function() { ... }, ... } 795root --> { profile: { ... }, ... } 796profile --> { friends: [ ... ], ... } 797friends[0] --> { name: "Jorge", ... } 798</code></pre> 799 800<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> 801 802<pre><code>// Set up a base context with global helpers 803var base = dust.makeBase({ 804 sayHello: function() { return "Hello!" } 805}); 806 807// Push to the base context at render time 808dust.render("index", base.push({foo: "bar"}), function(err, out) { 809 console.log(out); 810}); 811</code></pre> 812 813<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> 814 815<h3>Handlers</h3> 816 817<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> 818 819<pre><code>{ 820 name: function() { 821 return "Bob"; 822 } 823} 824</code></pre> 825 826<h4>Chunks</h4> 827 828<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> 829 830<pre><code>{ 831 name: function(chunk) { 832 return chunk.write("Bob"); 833 } 834} 835</code></pre> 836 837<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> 838 839<h4>Accessing the Context</h4> 840 841<p>Handlers have access to the context object:</p> 842 843<pre><code>{ 844 wrap: function(chunk, context) { 845 return chunk.write(context.get("foo")); 846 } 847} 848</code></pre> 849 850<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> 851 852<h4>Accessing Body Parameters</h4> 853 854<p>The <code>bodies</code> object provides access to any bodies defined within the calling block.</p> 855 856<pre><code>{#guide}foo{:else}bar{/guide} 857</code></pre> 858 859<p>The template above will either render "foo" or "bar" depending on the behavior of the handler below:</p> 860 861<pre><code>{ 862 guide: function(chunk, context, bodies) { 863 if (secret === 42) { 864 return chunk.render(bodies.block, context); 865 } else { 866 return chunk.render(bodies['else'], context); 867 } 868 } 869} 870</code></pre> 871 872<p><code>bodies.block</code> is a special parameter that returns the default (unnamed) block. <code>chunk.render</code> renders the chosen block.</p> 873 874<h4>Accessing Inline Parameters</h4> 875 876<p>The <code>params</code> object contains any inline parameters passed to a section tag:</p> 877 878<pre><code>{ 879 hello: function(chunk, context, bodies, params) { 880 if (params.greet === "true") { 881 return chunk.write("Hello!"); 882 } 883 return chunk; 884 } 885} 886</code></pre> 887 888<h4>Asynchronous Handlers</h4> 889 890<p>You may define handlers that execute asynchronously and in parallel:</p> 891 892<pre><code>{ 893 type: function(chunk) { 894 return chunk.map(function(chunk) { 895 setTimeout(function() { 896 chunk.end("Async"); 897 }); 898 }); 899 } 900} 901</code></pre> 902 903<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> 904 905<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> 906 907<h3>Reference</h3> 908 909<h4>Compiling</h4> 910 911<pre><code>dust.compile(source, name) 912</code></pre> 913 914<p>Compiles <code>source</code> into a JavaScript template string. Registers itself under <code>name</code> when evaluated.</p> 915 916<pre><code>dust.compileFn(source, [name]) 917</code></pre> 918 919<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> 920 921<pre><code>dust.optimizers 922</code></pre> 923 924<p>Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression:</p> 925 926<pre><code>dust.optimizers.format = function(ctx, node) { return node }; 927</code></pre> 928 929<h4>Loading</h4> 930 931<pre><code>dust.register(name, fn) 932</code></pre> 933 934<p>Used internally to register template function <code>fn</code> with the runtime environment. Override to customize the way Dust caches templates.</p> 935 936<pre><code>dust.onLoad(name, callback(err, out)) 937</code></pre> 938 939<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> 940 941<pre><code>dust.loadSource(source, [filename]) 942</code></pre> 943 944<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> 945 946<h4>Rendering</h4> 947 948<pre><code>dust.render(name, context, callback(error, output)) 949</code></pre> 950 951<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> 952 953<pre><code>dust.stream(name, context) 954</code></pre> 955 956<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> 957 958<pre><code>stream.on("data", listener(data)) 959stream.on("end", listener) 960stream.on("error", listener(error)) 961</code></pre> 962 963<p>Registers an event listener. Streams accept a single listener for a given event.</p> 964 965<pre><code>dust.renderSource(source, context, [callback(error, output)]) 966</code></pre> 967 968<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> 969 970<h4>Contexts</h4> 971 972<pre><code>dust.makeBase(object) 973</code></pre> 974 975<p>Manufactures a <code>dust.Context</code> instance with its global object set to <code>object</code>.</p> 976 977<pre><code>context.get(key) 978</code></pre> 979 980<p>Retrieves the value at <code>key</code> from the context stack.</p> 981 982<pre><code>context.push(head, [index], [length]) 983</code></pre> 984 985<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> 986 987<pre><code>context.rebase(head) 988</code></pre> 989 990<p>Returns a new context instance consisting only of the value at <code>head</code>, plus any previously defined global object.</p> 991 992<pre><code>context.current() 993</code></pre> 994 995<p>Returns the <code>head</code> of the context stack.</p> 996 997<h4>Chunks</h4> 998 999<p>The operations below always return a chunk object.</p> 1000 1001<pre><code>chunk.write(data) 1002</code></pre> 1003 1004<p>Writes <code>data</code> to this chunk's buffer.</p> 1005 1006<pre><code>chunk.map(callback(chunk)) 1007</code></pre> 1008 1009<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> 1010 1011<pre><code>chunk.end(data) 1012</code></pre> 1013 1014<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> 1015 1016<pre><code>chunk.tap(callback) 1017chunk.untap() 1018</code></pre> 1019 1020<p>Convenience methods for applying filters to a stream. See the <em>filter</em> demo for an example.</p> 1021 1022<pre><code>chunk.render(body, context) 1023</code></pre> 1024 1025<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> 1026 1027<pre><code>chunk.setError(error) 1028</code></pre> 1029 1030<p>Sets an error on this chunk and immediately flushes the output.</p> 1031 1032<pre><code>chunk.reference(elem, context, auto, filters) 1033chunk.section(elem, context, bodies, params) 1034chunk.exists(elem, context, bodies) 1035chunk.notexists(elem, context, bodies) 1036chunk.block(elem, context, bodies) 1037chunk.partial(elem, context) 1038chunk.helper(name, context, bodies, params) 1039</code></pre> 1040 1041<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> 1042 1043<h4>Utilities</h4> 1044 1045<pre><code>dust.filters 1046</code></pre> 1047 1048<p>Object containing built-in key filters. Can be customized with additional filters.</p> 1049 1050<pre><code>dust.helpers 1051</code></pre> 1052 1053<p>Object containing the built-in context helpers. These may also be customized.</p> 1054 1055<pre><code>dust.escapeHtml 1056</code></pre> 1057 1058<p>HTML escape function used by <code>dust.filters.h</code>.</p> 1059 1060<pre><code>dust.escapeJs 1061</code></pre> 1062 1063<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> 1064 1065<ul> 1066<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> 1067<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> 1068<li><strong>Streaming</strong>: Templates should allow (but not require) data to be flushed to the output in user-defined chunks.</li> 1069<li><strong>Browser and server compatible</strong>: Templates should render in both server and browser environments without hacks or extensive configuration.</li> 1070<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> 1071<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> 1072<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> 1073<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> 1074<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> 1075<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> 1076</ul> 1077 1078<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>