forked from akdubya/dustjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1078 lines (787 loc) · 38.1 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML><html><head><title>dust</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono:regular&subset=latin" rel="stylesheet" type="text/css"><style type="text/css">body {
font-family: 'Georgia', serif;
font-size: 18px;
margin: 0;
padding: 0;
}
p, h4, h3, .content ul {
line-height: 26px;
margin-top: 26px;
margin-bottom: 26px;
}
.content ul li {
margin-top: 13px;
margin-bottom: 13px;
}
h1, h2 {
line-height: 48px;
font-size: 32px;
font-weight: normal;
margin: 8px 0 8px 2%;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 1em;
}
h1, h2, pre, code, .console, .status, #nav, #tagline {
font-family: 'Droid Sans Mono', 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
}
a:link, a:visited {
color: #ef674a;
}
p code {
font-size: 16px;
line-height: 16px;
}
pre, .console {
background-color: #191919;
white-space: pre-wrap;
word-wrap: break-word;
}
.console {
font-size: 16px;
height: 270px;
color: #dddddd;
margin-top: 26px;
margin-bottom: 26px;
border: 1px solid #888;
resize: auto;
overflow: auto;
padding: 2px;
}
textarea {
width: 100%;
display: block;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#nav {
position: fixed;
top: 18px;
right: 2%;
font-size: 22px;
z-index: 99;
}
#nav a:link, #nav a:visited {
color: #eaf2d9;
}
#nav a {
text-decoration: none;
margin-left: 17px;
}
#nav a:last {
margin: 0;
}
#tagline {
position: absolute;
display: none;
top: 24px;
font-size: 14px;
}
#guide pre {
font-size: 16px;
line-height: 26px;
color: #dddddd;
padding: 26px;
margin: 26px 0;
}
#header, #demo {
clear: both;
}
.ok {
background-color: green;
}
.error {
background-color: red;
}
.pending {
background-color: yellow;
}
.status {
font-size: 14px;
padding: 2px;
margin-top: -24px;
}
.header, .content {
clear: both;
width: 100%;
overflow: hidden;
color: #ede6da;
}
.header {
clear: both;
width: 100%;
-webkit-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4);
-moz-box-shadow: 0px 4px 6px hsla(0, 0%, 0%, 0.4);
background-color: #581406;
}
.content {
background-color: #2d2929;
}
.left {
float: left;
width: 100%;
position: relative;
-webkit-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4);
-moz-box-shadow: 2px 0px 6px hsla(0, 0%, 0%, 0.4);
}
.content .left, .header .left {
right: 50%;
}
.content .left {
background-color: #272121;
}
.header, .col1, .col2 {
float: left;
position: relative;
overflow: hidden;
}
.col1 {
width: 96%;
left: 2%;
}
.left .header {
width: 100%;
left: 50%;
}
.left .col1 {
width: 46%;
left: 52%;
}
.left .col2 {
width: 46%;
left: 56%;
}
.docked {
position: fixed;
width: 100%;
top: 0;
background-color: hsla(10, 87%, 18%, 0.80);
z-index: 5;
}
code .keyword { font-weight: bold; color: #dd7522 }
code .string, code .regexp { color: #669933 }
code .class, code .special { }
code .number { color: #eddd3d }
code .comment { color: grey }</style><script src="vendor/ecma.js"></script><script src="vendor/jquery.min.js"></script><script src="vendor/jsdump.js"></script><script src="vendor/beautify.js"></script><script src="lib/dust.js"></script><script src="lib/parser.js"></script><script src="lib/compiler.js"></script><script src="test/examples.js"></script><script src="test/uutest.js"></script><script src="test/core.js"></script><script type="text/javascript">(function(){dust.register("select",body_0);function body_0(chk,ctx){return chk.write("<select style=\"clear: both;\">").section(ctx.get("examples"),ctx,{"block":body_1},null).write("</select>");}function body_1(chk,ctx){return chk.write("<option ").reference(ctx.get("selected"),ctx,"h").write(" value=\"").helper("idx",ctx,{"block":body_2},null).write("\">").reference(ctx.get("name"),ctx,"h").write("</option>");}function body_2(chk,ctx){return chk.reference(ctx.getPath(true,[]),ctx,"h");}return body_0;})();</script><script type="text/javascript">jsDump.parsers['function'] = function(fn) {
return fn.toString();
}
function renderDemo() {
var tmpl = dust.cache["demo"],
source = $('#input-context').val();
$('#output-text').empty();
if (tmpl && source) {
setPending('#input-context');
setPending('#output-text');
try {
eval("var context = " + source + ";");
if (typeof context === 'function') {
context = context();
}
dust.stream("demo", context)
.on('data', function(data) {
$('#output-text').append(dust.escapeHtml(data));
})
.on('end', function() {
setOkay('#input-context');
setOkay('#output-text');
})
.on('error', function(err) {
setError('#input-context', err);
});
} catch(err) {
setError('#input-context', err);
}
}
}
function setOkay(sel) {
$(sel).next()
.removeClass('pending')
.addClass('ok')
.html('Ready');
}
function setPending(sel) {
$(sel).next()
.removeClass('ok')
.removeClass('error')
.addClass('pending')
.html('Pending');
}
function setError(sel, err) {
$(sel).next()
.removeClass('pending')
.addClass('error')
.html(err.toString());
}
function dump(obj) {
return js_beautify(jsDump.parse(obj), {
indent_size: 2
});
}
function runSuite() {
var suite = new uutest.Suite({
start: function() {
$('#test-console').empty();
},
pass: function() {
$('#test-console').append(".");
},
fail: function() {
$('#test-console').append("F");
},
done: function(passed, failed, elapsed) {
$('#test-console').append("\n");
$('#test-console').append(passed + " passed " + failed + " failed " + "(" + elapsed + "ms)");
this.errors.forEach(function(err) {
$('#test-console').append("\n");
$('#test-console').append(dust.escapeHtml(dumpError(err)));
});
}
});
coreSetup(suite, dustExamples.slice(1), dust);
suite.run();
}
function dumpError(err) {
var out = err.testName + " -> ";
if (!err.message) {
err.message = jsDump.parse(err.expected)
+ " " + err.operator + " " + jsDump.parse(err.actual);
}
return out + err.stack;
}
$(document).ready(function() {
dustExamples.forEach(function(ex) {
dust.loadSource(dust.compile(ex.source, ex.name));
});
runSuite();
$('#tagline').empty().show().css({left: ($(window).width() * .02) + 125});
dust.loadSource(dust.compile(dustExamples[0].source, "intro"));
dust.stream("intro", dustExamples[0].context())
.on('data', function(data) {
$('#tagline').append(data);
})
.on('end', function() {
$('#tagline').delay(500).fadeOut('slow');
});
dust.render("select", {
examples: dustExamples,
selected: function(chk, ctx) {
if (ctx.current().name === "replace") return "selected";
}
}, function(err, output) {
$('#select').html(output);
});
$('#select > select').change(function() {
var idx = $(this).val();
$('#input-source').val(dustExamples[idx].source);
$('#input-context').val(dump(dustExamples[idx].context));
$('#input-source').change();
});
$('#input-source').change(function() {
setPending('#input-source');
try {
var compiled = dust.compile($(this).val(), "demo");
dust.loadSource(compiled);
$('#output-js').text(js_beautify(compiled, {
indent_size: 2
}));
setOkay('#input-source');
} catch(err) {
setError('#input-source', err);
return;
}
renderDemo();
});
$('#input-context').change(renderDemo);
var sections = $("body > div");
var cur_id;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop === 0) {
cur_id = undefined;
$('.docked').remove();
return;
}
sections.each(function(idx, section) {
var sectionTop = section.offsetTop,
sectionBottom = sectionTop + section.offsetHeight;
if (scrollTop >= sectionTop && scrollTop < sectionBottom) {
var $hdr = $(section).find('.header').clone();
if (section.id !== cur_id) {
cur_id = section.id;
$('.docked').remove();
$hdr.appendTo('body');
$hdr.addClass('docked');
}
return false;
}
});
});
$('#select > select').change();
$(window).scroll();
});</script></head><body><div id="dust" class="content"><div class="left"><div class="header"><h1>{dust}</h1><span id="tagline">asynchronous streaming templates for the browser and node.js</span></div><div id="nav"><a href="#dust">home</a><a href="#guide">guide</a><a href="#tests">tests</a><a href="#about">about</a><a href="http://github.com/akdubya/dustjs">code</a></div><div class="col1"><p>1. Select a template <span id="select"></span> or write your own:</p><textarea id="input-source" class="console"></textarea><div class="status ok">Ready</div><p>2. The compiled template registers itself by name:</p><pre class="console"><code id="output-js"></code></pre><p>When you're done messing around have a look at the guide.</p></div><div class="col2"><p>3. Control template behavior with contexts and helpers:</p><textarea id="input-context" class="console"></textarea><div class="status ok">Ready</div><p>4. Render or stream the result:</p><pre id="output-text" class="console"></pre></div></div></div><div id="guide" class="content"><div class="left"><div class="header"><h2>{guide}</h2></div><div id="syntax" class="col1"><p>Dust is a JavaScript templating engine designed to provide a clean separation between presentation and logic without sacrificing ease of use. It is particularly well-suited for asynchronous and streaming applications.</p>
<h3>Syntax</h3>
<p>Dust templates use two types of tags: <em>keys</em> and <em>sections</em>. Keys reference fields within the current view context. You can think of them as placeholders that allow the context to insert data into the template. Sections accept template blocks that may be enumerated, filtered or transformed in various ways.</p>
<h3>Keys</h3>
<p>To reference a key from the view context within the template, enclose the key in curly braces. For example, given the template below:</p>
<pre><code>Hello {name}!
</code></pre>
<p>And the following view context:</p>
<pre><code>{ name: "Fred" }
</code></pre>
<p>The resulting output would be:</p>
<pre><code>Hello Fred!
</code></pre>
<p>If the <em>name</em> key cannot be found in the view, Dust outputs an empty string:</p>
<pre><code>Hello !
</code></pre>
<p>Generally, Dust casts whatever values it finds to strings. If Dust encounters a handler function it calls the function, passing in the current state of the template.</p>
<h4>Filters</h4>
<p>By default, the content of all key tags is HTML escaped, so assuming the <em>name</em> key above resolves to a dangerous script tag:</p>
<pre><code><script>alert('I am evil!')</script>
</code></pre>
<p>This would be rendered as:</p>
<pre><code>&lt;script&gt;alert('I am evil!')&lt;/script&gt;
</code></pre>
<p>To disable auto-escaping, append a pipe character '|' and an 's' to the end of the tag identifier, like so:</p>
<pre><code>Hello {name|s}
</code></pre>
<p>There are several other built-in filters: <code>h</code> forces HTML escaping, <code>j</code> escapes JavaScript strings, <code>u</code> proxies to JavaScript's built-in <code>encodeURI</code>, and <code>uc</code> proxies to JavaScript's <code>encodeURIComponent</code>. Filters can also be chained together like so:</p>
<pre><code>Hello {name|s|h|u}
</code></pre>
<p>When chained in this manner, filters are applied from left to right. Filters do not accept arguments; if you need more sophisticated behavior use a section tag instead.</p>
<h3>Sections</h3>
<p>Keys are fine for simple lookups, but suppose the view context contains a <em>friends</em> field which resolves to an array of objects containing <em>name</em> and <em>age</em> fields. This is where section tags are useful.</p>
<pre><code>{#friends}
{name}, {age}{~n}
{/friends}
</code></pre>
<p>Here, the section begins with <code>{#friends}</code> and ends with <code>{/friends}</code>. Dust's default behavior is to enumerate over the array, passing each object in the array to the block. With a the following view context:</p>
<pre><code>{
friends: [
{ name: "Moe", age: 37 },
{ name: "Larry", age: 39 },
{ name: "Curly", age: 35 }
]
}
</code></pre>
<p>The output is as one might expect:</p>
<pre><code>Moe, 37
Larry, 39
Curly, 35
</code></pre>
<p>When <em>friends</em> resolves to a value or object instead of an array, Dust sets the current context to the value and renders the block one time. If <em>friends</em> resolves to a custom handler function, the function is given control over the section's behavior.</p>
<p>Dust outputs nothing if the friends key is empty or nonexistent. Let's change that by inserting an <code>{:else}</code> tag, which tells Dust to render an alternate template block when a section key resolves to a falsy value:</p>
<pre><code>{#friends}
{name}, {age}{~n}
{:else}
You have no friends!
{/friends}
</code></pre>
<p>Now when the friends key is empty or nonexistent we get the following:</p>
<pre><code>You have no friends!
</code></pre>
<p>Internally, Dust builds a stack of contexts as templates delve deeper into nested sections. If a key is not found within the current context, Dust looks for the key within the parent context, and its parent, and so on.</p>
<p>Self-closing section tags are allowed, so the template code below is permissible (although in this case it won't render anything):</p>
<pre><code>{#friends/}
</code></pre>
<h4>Paths</h4>
<p>Paths allow you to reference keys relative to the current context. </p>
<pre><code>{#names}{.} {/names}
</code></pre>
<p>The dot notation above lets the template reference the current context implicitly, so given an array of strings:</p>
<pre><code>{ names: ["Moe", "Larry", "Curly"] }
</code></pre>
<p>The template block outputs each string in the array.</p>
<pre><code>Moe Larry Curly
</code></pre>
<p>Paths can also be used to reach into nested contexts:</p>
<pre><code>{foo.bar}
</code></pre>
<p>Or to constrain lookups to the current section scope:</p>
<pre><code>{.foo}
</code></pre>
<p>To avoid brittle and confusing references, paths never backtrack up the context stack. If you need to drill into a key available within the parent context, pass the key as a parameter.</p>
<h4>Inline Parameters</h4>
<p>Inline parameters appear within the section's opening tag. Parameters are separated by a single space. By default, inline parameters merge values into the section's view context:</p>
<pre><code>{#profile bar="baz" bing="bong"}
{name}, {bar}, {bing}
{/profile}
</code></pre>
<p>Assuming <em>name</em> within the profile section resolves to "Fred", the output would be:</p>
<pre><code>Fred, baz, bong
</code></pre>
<p>Inline parameters may be used to alias keys that conflict between parent and child contexts:</p>
<pre><code>{name}{~n}
{#profile root_name=name}
{name}, {root_name}
{/profile}
</code></pre>
<p>Note here that we're passing in a key rather than a string literal. If the context is as follows:</p>
<pre><code>{
name: "Foo",
profile: {
name: "Bar"
}
}
</code></pre>
<p>The output will be:</p>
<pre><code>Foo
Bar, Foo
</code></pre>
<p>Parameters accept interpolated string literals as values:</p>
<pre><code>{#snippet id="{name}_id"/}
</code></pre>
<h4>Body Parameters</h4>
<p>Unlike inline parameters, which modify the context, body parameters pass named template blocks to handler functions. Body parameters are useful for implementing striping or other complex behaviors that might otherwise involve manually assembling strings within your view functions. The only body parameter with default behavior is the <code>{:else}</code> tag as seen above.</p>
<h4>Contexts</h4>
<p>Normally, upon encountering a section tag Dust merges the section's context with the parent context. Sometimes it can be useful to manually set the context provided to a section. Sections accept a context argument for this purpose:</p>
<pre><code>{#list:projects}{name}{/list}
</code></pre>
<p>Here, we're providing an array of <em>projects</em> to the <em>list</em> section, which might be a special helper defined on the view. If <em>list</em> is not a function but some other value instead, its parent context is simply set to <em>projects</em>.</p>
<h4>Special Sections</h4>
<p>In addition to the standard hashed (<code>#</code>) section tag, Dust provides a few section tags with special semantics, namely the <em>exists</em> tag (<code>?</code>), the <em>notexists</em> tag (<code>^</code>), and the context helpers tag (<code>@</code>). These tags make it easier to work with plain JSON data without additional helpers.</p>
<p>The exists and notexists sections check for the existence (in the falsy sense) of a key within the current context. They do not alter the current context, making it possible to, for instance, check that an array is non-empty before wrapping it in HTML list tags:</p>
<pre><code>{?tags}
<ul>
{#tags}
<li>{.}</li>
{/tags}
</ul>
{:else}
No Tags!
{/tags}
</code></pre>
<p>Unlike regular sections, conditional sections do not evaluate functions defined on the view. In those cases you'll still have to write your own handlers.</p>
<p>The context helpers tag provides a couple of convenience functions to support iteration. The <code>sep</code> tag prints the enclosed block for every value except for the last. The <code>idx</code> tag passes the numerical index of the current element to the enclosed block.</p>
<pre><code>{#names}{.}{@idx}{.}{/idx}{@sep}, {/sep}{/names}
</code></pre>
<p>The template above might output something like:</p>
<pre><code>Moe0, Larry1, Curly2
</code></pre>
<h3>Partials</h3>
<p>Partials, also known as template includes, allow you to compose templates at runtime.</p>
<pre><code>{>profile/}
</code></pre>
<p>The block above looks for a template named "profile" and inserts its output into the parent template. Like sections, partials inherit the current context. And like sections, partials accept a context argument:</p>
<pre><code>{>profile:user/}
</code></pre>
<p>Partial tags also accept string literals and interpolated string literals as keys:</p>
<pre><code>{>"path/to/comments.dust.html"/}
{>"posts/{type}.dust.html"/}
</code></pre>
<p>This is useful when you're retrieving templates from the filesystem and the template names wouldn't otherwise be valid identifiers, or when selecting templates dynamically based on information from the view context.</p>
<h3>Blocks and Inline Partials</h3>
<p>Often you'll want to have a template inherit the bulk of its content from a common base template. Dust solves this problem via blocks and inline partials. When placed within a template, blocks allow you to define snippets of template code that may be overriden by any templates that reference this template:</p>
<pre><code>Start{~n}
{+title}
Base Title
{/title}
{~n}
{+main}
Base Content
{/main}
{~n}
End
</code></pre>
<p>Notice the special syntax for blocks: <code>{+block} ... {/block}</code>. When this template is rendered standalone, Dust simply renders the content within the blocks:</p>
<pre><code>Start
Base Title
Base Content
End
</code></pre>
<p>But when the template is invoked from another template that contains inline partial tags (<code>{<snippet} ... {/snippet}</code>):</p>
<pre><code>{>base_template/}
{<title}
Child Title
{/title}
{<main}
Child Content
{/main}
</code></pre>
<p>Dust overrides the block contents of the base template:</p>
<pre><code>Start
Child Title
Child Content
End
</code></pre>
<p>A block may be self-closing (<code>{+block/}</code>), in which case it is not displayed unless a calling template overrides the content of the block. Inline partials never output content themselves, and are always global to the template in which they are defined, so the order of their definition has no significance. They are passed to all templates invoked by the template in which they are defined.</p>
<p>Note that blocks can be used to render inline partials that are defined within the same template. This is useful when you want to use the same template to serve AJAX requests and regular requests:</p>
<pre><code>{^xhr}
{>base_template/}
{:else}
{+main/}
{/xhr}
{<title}
Child Title
{/title}
{<main}
Child Content
{/main}
</code></pre>
<h3>Static Text</h3>
<p>The Dust parser is finely tuned to minimize the amount of escaping that needs to be done within static text. Any text that does not closely resemble a Dust tag is considered static and will be passed through untouched to the template's output. This makes Dust suitable for use in templating many different formats. In order to be recognized as such, Dust tags should not contain extraneous whitespace and newlines.</p>
<h4>Special Characters</h4>
<p>Depending on whitespace and delimeter settings, it is sometimes necessary to include escape tags within static text. Escape tags begin with a tilde (<code>~</code>), followed by a key identifying the desired escape sequence. Currently newline (<code>n</code>), carriage return (<code>r</code>), space (<code>s</code>), left brace (<code>lb</code>) and right brace (<code>rb</code>) are supported. For example:</p>
<pre><code>Hello World!{~n}
</code></pre>
<p>Inserts a newline after the text. By default, Dust compresses whitespace by eliminating newlines and indentation. This behavior can be toggled at compile time.</p>
<h4>Comments</h4>
<p>Comments, which do not appear in template output, begin and end with a bang (<code>!</code>):</p>
<pre><code>{!
Multiline
{#foo}{bar}{/foo}
!}
{!before!}Hello{!after!}
</code></pre>
<p>The template above would render as follows:</p>
<pre><code>Hello
</code></pre></div><div id="api" class="col2"><p>A pure JavaScript library, Dust is runs in both browser-side and server-side environments. Dust templates are compiled and then loaded where they are needed along with the runtime library. The library doesn't make any assumptions about how templates are loaded; you are free to integrate templating into your environment as you see fit.</p>
<h3>Installation</h3>
<p>To run Dust within Node.js, first install via <a href="http://github.com/isaacs/npm">npm</a>:</p>
<pre><code>npm install dust
</code></pre>
<p>Then, within your Node script or the REPL:</p>
<pre><code>var dust = require('dust');
</code></pre>
<p>This will import everything needed to parse, compile and render templates. To render Dust templates in the browser, grab the runtime distribution and include it in your script tags along with your compiled templates:</p>
<pre><code><script src="dust-core-0.3.0.min.js"></script>
<script src="compiled_templates.js"></script>
</code></pre>
<p>Include the full distribution if you want to compile templates within the browser (as in the online demo):</p>
<pre><code><script src="dust-full-0.3.0.min.js"></script>
</code></pre>
<p>Precompilation is the recommended approach for general use.</p>
<h3>Compiling Templates</h3>
<p>Use <code>dust.compile</code> to compile a template body into a string of JavaScript source code:</p>
<pre><code>var compiled = dust.compile("Hello {name}!", "intro");
</code></pre>
<p>The variable <code>compiled</code> now contains the following string:</p>
<pre><code>'(function(){dust.register("intro",body_0) ...'
</code></pre>
<p>If you save this source to a file and include the file in your HTML script tags, the compiled template will automatically register itself with the local runtime, under the name "intro". To evaluate a compiled template string manually, use <code>dust.loadSource</code>:</p>
<pre><code>dust.loadSource(compiled);
</code></pre>
<p>The template is now available within the <code>dust.cache</code> object.</p>
<h3>Rendering Templates</h3>
<p>The rendering engine provides both callback and streaming interfaces.</p>
<h4>The Callback Interface</h4>
<p>To render a template, call <code>dust.render</code> with the template name, a context object and a callback function:</p>
<pre><code>dust.render("intro", {name: "Fred"}, function(err, out) {
console.log(out);
});
</code></pre>
<p>The code above will write the following to the console:</p>
<pre><code>Hello Fred!
</code></pre>
<h4>The Streaming Interface</h4>
<p>Templates may also be streamed. <code>dust.stream</code> returns a handler very similar to a Node <code>EventEmitter</code>:</p>
<pre><code>dust.stream("index", context)
.on("data", function(data) {
console.log(data);
})
.on("end", function() {
console.log("I'm finished!");
})
.on("error", function(err) {
console.log("Something terrible happened!");
});
</code></pre>
<p>When used with specially crafted context handlers, the streaming interface provides chunked template rendering.</p>
<h3>Contexts</h3>
<p>The context is a special object that handles variable lookups and controls template behavior. It is the interface between your application logic and your templates. The context can be visualized as a stack of objects that grows as we descend into nested sections:</p>
<pre><code>global --> { helper: function() { ... }, ... }
root --> { profile: { ... }, ... }
profile --> { friends: [ ... ], ... }
friends[0] --> { name: "Jorge", ... }
</code></pre>
<p>When looking up a key, Dust searches the context stack from the bottom up. There is no need to merge helper functions into the template data; instead, create a base context onto which you can push your local template data:</p>
<pre><code>// Set up a base context with global helpers
var base = dust.makeBase({
sayHello: function() { return "Hello!" }
});
// Push to the base context at render time
dust.render("index", base.push({foo: "bar"}), function(err, out) {
console.log(out);
});
</code></pre>
<p>Dust does not care how your reference objects are built. You may, for example, push prototyped objects onto the stack. The system leaves the <code>this</code> keyword intact when calling handler functions on your objects.</p>
<h3>Handlers</h3>
<p>When Dust encounters a function in the context, it calls the function, passing in arguments that reflect the current state of the template. In the simplest case, a handler can pass a value back to the template engine:</p>
<pre><code>{
name: function() {
return "Bob";
}
}
</code></pre>
<h4>Chunks</h4>
<p>But handlers can do much more than return values: they have complete control over the flow of the template, using the same API Dust uses internally. For example, the handler below writes a string directly to the current template chunk:</p>
<pre><code>{
name: function(chunk) {
return chunk.write("Bob");
}
}
</code></pre>
<p>A <code>Chunk</code> is a Dust primitive for controlling the flow of the template. Depending upon the behaviors defined in the context, templates may output one or more chunks during rendering. A handler that writes to a chunk directly must return the modified chunk.</p>
<h4>Accessing the Context</h4>
<p>Handlers have access to the context object:</p>
<pre><code>{
wrap: function(chunk, context) {
return chunk.write(context.get("foo"));
}
}
</code></pre>
<p><code>context.get("foo")</code> searches for <em>foo</em> within the context stack. <code>context.current()</code> retrieves the value most recently pushed onto the context stack.</p>
<h4>Accessing Body Parameters</h4>
<p>The <code>bodies</code> object provides access to any bodies defined within the calling block.</p>
<pre><code>{#guide}foo{:else}bar{/guide}
</code></pre>
<p>The template above will either render "foo" or "bar" depending on the behavior of the handler below:</p>
<pre><code>{
guide: function(chunk, context, bodies) {
if (secret === 42) {
return chunk.render(bodies.block, context);
} else {
return chunk.render(bodies['else'], context);
}
}
}
</code></pre>
<p><code>bodies.block</code> is a special parameter that returns the default (unnamed) block. <code>chunk.render</code> renders the chosen block.</p>
<h4>Accessing Inline Parameters</h4>
<p>The <code>params</code> object contains any inline parameters passed to a section tag:</p>
<pre><code>{
hello: function(chunk, context, bodies, params) {
if (params.greet === "true") {
return chunk.write("Hello!");
}
return chunk;
}
}
</code></pre>
<h4>Asynchronous Handlers</h4>
<p>You may define handlers that execute asynchronously and in parallel:</p>
<pre><code>{
type: function(chunk) {
return chunk.map(function(chunk) {
setTimeout(function() {
chunk.end("Async");
});
});
}
}
</code></pre>
<p><code>chunk.map</code> tells Dust to manufacture a new chunk, reserving a slot in the output stream before continuing on to render the rest of the template. You must (eventually) call <code>chunk.end()</code> on a mapped chunk to weave its content back into the stream.</p>
<p><code>chunk.map</code> provides a convenient way to split up templates rendered via <code>dust.stream</code>. For example, you might wrap the head of an HTML document in a special <code>{#head} ... {/head}</code> tag that is flushed to the browser before the rest of the body has finished rendering.</p>
<h3>Reference</h3>
<h4>Compiling</h4>
<pre><code>dust.compile(source, name)
</code></pre>
<p>Compiles <code>source</code> into a JavaScript template string. Registers itself under <code>name</code> when evaluated.</p>
<pre><code>dust.compileFn(source, [name])
</code></pre>
<p>Compiles <code>source</code> directly into a JavaScript function that takes a context and an optional callback (see <code>dust.renderSource</code>). Registers the template under <code>name</code> if this argument is supplied.</p>
<pre><code>dust.optimizers
</code></pre>
<p>Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression:</p>
<pre><code>dust.optimizers.format = function(ctx, node) { return node };
</code></pre>
<h4>Loading</h4>
<pre><code>dust.register(name, fn)
</code></pre>
<p>Used internally to register template function <code>fn</code> with the runtime environment. Override to customize the way Dust caches templates.</p>
<pre><code>dust.onLoad(name, callback(err, out))
</code></pre>
<p>By default Dust returns a "template not found" error when a named template cannot be located in the cache. Override <code>onLoad</code> to specify a fallback loading mechanism (e.g., to load templates from the filesystem or a database).</p>
<pre><code>dust.loadSource(source, [filename])
</code></pre>
<p>Evaluates compiled <code>source</code> string. In Node.js, evaluates <code>source</code> as if it were loaded from <code>filename</code>. <code>filename</code> is optional.</p>
<h4>Rendering</h4>
<pre><code>dust.render(name, context, callback(error, output))
</code></pre>
<p>Renders the named template and calls <code>callback</code> on completion. <code>context</code> may be a plain object or an instance of <code>dust.Context</code>.</p>
<pre><code>dust.stream(name, context)
</code></pre>
<p>Streams the named template. <code>context</code> may be a plain object or an instance of <code>dust.Context</code>. Returns an instance of <code>dust.Stream</code>.</p>
<pre><code>stream.on("data", listener(data))
stream.on("end", listener)
stream.on("error", listener(error))
</code></pre>
<p>Registers an event listener. Streams accept a single listener for a given event.</p>
<pre><code>dust.renderSource(source, context, [callback(error, output)])
</code></pre>
<p>Compiles and renders <code>source</code>, invoking <code>callback</code> on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required.</p>
<h4>Contexts</h4>
<pre><code>dust.makeBase(object)
</code></pre>
<p>Manufactures a <code>dust.Context</code> instance with its global object set to <code>object</code>.</p>
<pre><code>context.get(key)
</code></pre>
<p>Retrieves the value at <code>key</code> from the context stack.</p>
<pre><code>context.push(head, [index], [length])
</code></pre>
<p>Pushes an arbitrary value onto the context stack and returns a new context instance. Specify <code>index</code> and/or <code>length</code> to enable enumeration helpers.</p>
<pre><code>context.rebase(head)
</code></pre>
<p>Returns a new context instance consisting only of the value at <code>head</code>, plus any previously defined global object.</p>
<pre><code>context.current()
</code></pre>
<p>Returns the <code>head</code> of the context stack.</p>
<h4>Chunks</h4>
<p>The operations below always return a chunk object.</p>