818
Du
dustymarkdown / files
dustymarkdown / node_modules / dust / docs / api.md
11.0 KB
1A 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. 2 3### Installation 4 5To run Dust within Node.js, first install via [npm](http://github.com/isaacs/npm): 6 7 npm install dust 8 9Then, within your Node script or the REPL: 10 11 var dust = require('dust'); 12 13This 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: 14 15 <script src="dust-core-0.3.0.min.js"></script> 16 <script src="compiled_templates.js"></script> 17 18Include the full distribution if you want to compile templates within the browser (as in the online demo): 19 20 <script src="dust-full-0.3.0.min.js"></script> 21 22Precompilation is the recommended approach for general use. 23 24### Compiling Templates 25 26Use `dust.compile` to compile a template body into a string of JavaScript source code: 27 28 var compiled = dust.compile("Hello {name}!", "intro"); 29 30The variable `compiled` now contains the following string: 31 32 '(function(){dust.register("intro",body_0) ...' 33 34If 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`: 35 36 dust.loadSource(compiled); 37 38The template is now available within the `dust.cache` object. 39 40### Rendering Templates 41 42The rendering engine provides both callback and streaming interfaces. 43 44#### The Callback Interface 45 46To render a template, call `dust.render` with the template name, a context object and a callback function: 47 48 dust.render("intro", {name: "Fred"}, function(err, out) { 49 console.log(out); 50 }); 51 52The code above will write the following to the console: 53 54 Hello Fred! 55 56#### The Streaming Interface 57 58Templates may also be streamed. `dust.stream` returns a handler very similar to a Node `EventEmitter`: 59 60 dust.stream("index", context) 61 .on("data", function(data) { 62 console.log(data); 63 }) 64 .on("end", function() { 65 console.log("I'm finished!"); 66 }) 67 .on("error", function(err) { 68 console.log("Something terrible happened!"); 69 }); 70 71When used with specially crafted context handlers, the streaming interface provides chunked template rendering. 72 73### Contexts 74 75The 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: 76 77 global --> { helper: function() { ... }, ... } 78 root --> { profile: { ... }, ... } 79 profile --> { friends: [ ... ], ... } 80 friends[0] --> { name: "Jorge", ... } 81 82When 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: 83 84 // Set up a base context with global helpers 85 var base = dust.makeBase({ 86 sayHello: function() { return "Hello!" } 87 }); 88 89 // Push to the base context at render time 90 dust.render("index", base.push({foo: "bar"}), function(err, out) { 91 console.log(out); 92 }); 93 94Dust 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. 95 96### Handlers 97 98When 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: 99 100 { 101 name: function() { 102 return "Bob"; 103 } 104 } 105 106#### Chunks 107 108But 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: 109 110 { 111 name: function(chunk) { 112 return chunk.write("Bob"); 113 } 114 } 115 116A `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. 117 118#### Accessing the Context 119 120Handlers have access to the context object: 121 122 { 123 wrap: function(chunk, context) { 124 return chunk.write(context.get("foo")); 125 } 126 } 127 128`context.get("foo")` searches for _foo_ within the context stack. `context.current()` retrieves the value most recently pushed onto the context stack. 129 130#### Accessing Body Parameters 131 132The `bodies` object provides access to any bodies defined within the calling block. 133 134 {#guide}foo{:else}bar{/guide} 135 136The template above will either render "foo" or "bar" depending on the behavior of the handler below: 137 138 { 139 guide: function(chunk, context, bodies) { 140 if (secret === 42) { 141 return chunk.render(bodies.block, context); 142 } else { 143 return chunk.render(bodies['else'], context); 144 } 145 } 146 } 147 148`bodies.block` is a special parameter that returns the default (unnamed) block. `chunk.render` renders the chosen block. 149 150#### Accessing Inline Parameters 151 152The `params` object contains any inline parameters passed to a section tag: 153 154 { 155 hello: function(chunk, context, bodies, params) { 156 if (params.greet === "true") { 157 return chunk.write("Hello!"); 158 } 159 return chunk; 160 } 161 } 162 163#### Asynchronous Handlers 164 165You may define handlers that execute asynchronously and in parallel: 166 167 { 168 type: function(chunk) { 169 return chunk.map(function(chunk) { 170 setTimeout(function() { 171 chunk.end("Async"); 172 }); 173 }); 174 } 175 } 176 177`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. 178 179`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. 180 181### Reference 182 183#### Compiling 184 185 dust.compile(source, name) 186 187Compiles `source` into a JavaScript template string. Registers itself under `name` when evaluated. 188 189 dust.compileFn(source, [name]) 190 191Compiles `source` directly into a JavaScript function that takes a context and an optional callback (see `dust.renderSource`). Registers the template under `name` if this argument is supplied. 192 193 dust.optimizers 194 195Object containing functions that transform the parse-tree before the template is compiled. To disable whitespace compression: 196 197 dust.optimizers.format = function(ctx, node) { return node }; 198 199#### Loading 200 201 dust.register(name, fn) 202 203Used internally to register template function `fn` with the runtime environment. Override to customize the way Dust caches templates. 204 205 dust.onLoad(name, callback(err, out)) 206 207By default Dust returns a "template not found" error when a named template cannot be located in the cache. Override `onLoad` to specify a fallback loading mechanism (e.g., to load templates from the filesystem or a database). 208 209 dust.loadSource(source, [filename]) 210 211Evaluates compiled `source` string. In Node.js, evaluates `source` as if it were loaded from `filename`. `filename` is optional. 212 213#### Rendering 214 215 dust.render(name, context, callback(error, output)) 216 217Renders the named template and calls `callback` on completion. `context` may be a plain object or an instance of `dust.Context`. 218 219 dust.stream(name, context) 220 221Streams the named template. `context` may be a plain object or an instance of `dust.Context`. Returns an instance of `dust.Stream`. 222 223 stream.on("data", listener(data)) 224 stream.on("end", listener) 225 stream.on("error", listener(error)) 226 227Registers an event listener. Streams accept a single listener for a given event. 228 229 dust.renderSource(source, context, [callback(error, output)]) 230 231Compiles and renders `source`, invoking `callback` on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. 232 233#### Contexts 234 235 dust.makeBase(object) 236 237Manufactures a `dust.Context` instance with its global object set to `object`. 238 239 context.get(key) 240 241Retrieves the value at `key` from the context stack. 242 243 context.push(head, [index], [length]) 244 245Pushes an arbitrary value onto the context stack and returns a new context instance. Specify `index` and/or `length` to enable enumeration helpers. 246 247 context.rebase(head) 248 249Returns a new context instance consisting only of the value at `head`, plus any previously defined global object. 250 251 context.current() 252 253Returns the `head` of the context stack. 254 255#### Chunks 256 257The operations below always return a chunk object. 258 259 chunk.write(data) 260 261Writes `data` to this chunk's buffer. 262 263 chunk.map(callback(chunk)) 264 265Creates a new chunk and passes it to `callback`. Use `map` to wrap asynchronous functions and to partition the template for streaming. 266 267 chunk.end(data) 268 269Writes `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. 270 271 chunk.tap(callback) 272 chunk.untap() 273 274Convenience methods for applying filters to a stream. See the _filter_ demo for an example. 275 276 chunk.render(body, context) 277 278Renders a template block, such as a default block or an `else` block. Basically equivalent to `body(chunk, context)`. 279 280 chunk.setError(error) 281 282Sets an error on this chunk and immediately flushes the output. 283 284 chunk.reference(elem, context, auto, filters) 285 chunk.section(elem, context, bodies, params) 286 chunk.exists(elem, context, bodies) 287 chunk.notexists(elem, context, bodies) 288 chunk.block(elem, context, bodies) 289 chunk.partial(elem, context) 290 chunk.helper(name, context, bodies, params) 291 292These 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. 293 294#### Utilities 295 296 dust.filters 297 298Object containing built-in key filters. Can be customized with additional filters. 299 300 dust.helpers 301 302Object containing the built-in context helpers. These may also be customized. 303 304 dust.escapeHtml 305 306HTML escape function used by `dust.filters.h`. 307 308 dust.escapeJs 309 310JavaScript string escape function used by `dust.filters.j`.