818
Du
dustymarkdown / files
dustymarkdown / node_modules / dust / docs / syntax.md
10.8 KB
1Dust 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. 2 3### Syntax 4 5Dust 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. 6 7### Keys 8 9To reference a key from the view context within the template, enclose the key in curly braces. For example, given the template below: 10 11 Hello {name}! 12 13And the following view context: 14 15 { name: "Fred" } 16 17The resulting output would be: 18 19 Hello Fred! 20 21If the _name_ key cannot be found in the view, Dust outputs an empty string: 22 23 Hello ! 24 25Generally, 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. 26 27#### Filters 28 29By default, the content of all key tags is HTML escaped, so assuming the _name_ key above resolves to a dangerous script tag: 30 31 <script>alert('I am evil!')</script> 32 33This would be rendered as: 34 35 <script>alert('I am evil!')</script> 36 37To disable auto-escaping, append a pipe character '|' and an 's' to the end of the tag identifier, like so: 38 39 Hello {name|s} 40 41There 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: 42 43 Hello {name|s|h|u} 44 45When 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. 46 47### Sections 48 49Keys 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. 50 51 {#friends} 52 {name}, {age}{~n} 53 {/friends} 54 55Here, 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: 56 57 { 58 friends: [ 59 { name: "Moe", age: 37 }, 60 { name: "Larry", age: 39 }, 61 { name: "Curly", age: 35 } 62 ] 63 } 64 65The output is as one might expect: 66 67 Moe, 37 68 Larry, 39 69 Curly, 35 70 71When _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. 72 73Dust 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: 74 75 {#friends} 76 {name}, {age}{~n} 77 {:else} 78 You have no friends! 79 {/friends} 80 81Now when the friends key is empty or nonexistent we get the following: 82 83 You have no friends! 84 85Internally, 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. 86 87Self-closing section tags are allowed, so the template code below is permissible (although in this case it won't render anything): 88 89 {#friends/} 90 91#### Paths 92 93Paths allow you to reference keys relative to the current context. 94 95 {#names}{.} {/names} 96 97The dot notation above lets the template reference the current context implicitly, so given an array of strings: 98 99 { names: ["Moe", "Larry", "Curly"] } 100 101The template block outputs each string in the array. 102 103 Moe Larry Curly 104 105Paths can also be used to reach into nested contexts: 106 107 {foo.bar} 108 109Or to constrain lookups to the current section scope: 110 111 {.foo} 112 113To 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. 114 115#### Inline Parameters 116 117Inline 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: 118 119 {#profile bar="baz" bing="bong"} 120 {name}, {bar}, {bing} 121 {/profile} 122 123Assuming _name_ within the profile section resolves to "Fred", the output would be: 124 125 Fred, baz, bong 126 127Inline parameters may be used to alias keys that conflict between parent and child contexts: 128 129 {name}{~n} 130 {#profile root_name=name} 131 {name}, {root_name} 132 {/profile} 133 134Note here that we're passing in a key rather than a string literal. If the context is as follows: 135 136 { 137 name: "Foo", 138 profile: { 139 name: "Bar" 140 } 141 } 142 143The output will be: 144 145 Foo 146 Bar, Foo 147 148Parameters accept interpolated string literals as values: 149 150 {#snippet id="{name}_id"/} 151 152#### Body Parameters 153 154Unlike 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. 155 156#### Contexts 157 158Normally, 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: 159 160 {#list:projects}{name}{/list} 161 162Here, 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_. 163 164#### Special Sections 165 166In 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. 167 168The 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: 169 170 {?tags} 171 <ul> 172 {#tags} 173 <li>{.}</li> 174 {/tags} 175 </ul> 176 {:else} 177 No Tags! 178 {/tags} 179 180Unlike regular sections, conditional sections do not evaluate functions defined on the view. In those cases you'll still have to write your own handlers. 181 182The 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. 183 184 {#names}{.}{@idx}{.}{/idx}{@sep}, {/sep}{/names} 185 186The template above might output something like: 187 188 Moe0, Larry1, Curly2 189 190### Partials 191 192Partials, also known as template includes, allow you to compose templates at runtime. 193 194 {>profile/} 195 196The 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: 197 198 {>profile:user/} 199 200Partial tags also accept string literals and interpolated string literals as keys: 201 202 {>"path/to/comments.dust.html"/} 203 {>"posts/{type}.dust.html"/} 204 205 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. 206 207### Blocks and Inline Partials 208 209Often 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: 210 211 Start{~n} 212 {+title} 213 Base Title 214 {/title} 215 {~n} 216 {+main} 217 Base Content 218 {/main} 219 {~n} 220 End 221 222Notice the special syntax for blocks: `{+block} ... {/block}`. When this template is rendered standalone, Dust simply renders the content within the blocks: 223 224 Start 225 Base Title 226 Base Content 227 End 228 229But when the template is invoked from another template that contains inline partial tags (`{<snippet} ... {/snippet}`): 230 231 {>base_template/} 232 {<title} 233 Child Title 234 {/title} 235 {<main} 236 Child Content 237 {/main} 238 239Dust overrides the block contents of the base template: 240 241 Start 242 Child Title 243 Child Content 244 End 245 246A 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. 247 248Note 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: 249 250 {^xhr} 251 {>base_template/} 252 {:else} 253 {+main/} 254 {/xhr} 255 {<title} 256 Child Title 257 {/title} 258 {<main} 259 Child Content 260 {/main} 261 262### Static Text 263 264The 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. 265 266#### Special Characters 267 268Depending 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: 269 270 Hello World!{~n} 271 272Inserts a newline after the text. By default, Dust compresses whitespace by eliminating newlines and indentation. This behavior can be toggled at compile time. 273 274#### Comments 275 276Comments, which do not appear in template output, begin and end with a bang (`!`): 277 278 {! 279 Multiline 280 {#foo}{bar}{/foo} 281 !} 282 {!before!}Hello{!after!} 283 284The template above would render as follows: 285 286 Hello