An important need in developing a multi-page web application is to have common elements of the pages defined just once and shared by all pages (DRY - Don’t repeat yourself). Dust provides this with the concept of blocks and inline partials. Consider a common case where several pages share a header and footer but have different body content.

Blocks in the base template can contain default content and a child template can override that content.

{+name}default Content{/name}.

In the following example, the base template has three blocks: pageHeader, bodyContent, and pageFooter. The pageHeader and pageFooter have default content that is shown if the child template does not override them. You’ll notice below that without a child template, the base template renders the default header and footer content, but no body content.

<div class="page"> <h1>{+pageHeader}LinkedIn{/pageHeader}</h1> <div class="bodyContent"> {+bodyContent/} </div> <div class="footer"> {+pageFooter} <a href="/contactUs">Contact Us</a> {/pageFooter} </div> </div> {}

Now that we have defined a base template with the named blocks pageHeader, bodyContent, pageFooter, let’s look at how a child template can use it to supply body content and override the pageFooter. First, insert the base template as a partial. Then use one or more “inline partials” defining the values for the named blocks in the template. You’ll see in the example below that we override the bodyContent block and the pageFooter block. The pageHeader block is not overridden, so it shows its default content.

{! First, insert the base template as a partial !} {>"base_template"/} {<bodyContent} <p>Your body content</p> {/bodyContent} {<pageFooter} This is a NEW footer {/pageFooter} {}

Warning: inline partials’ names are global to that template chain.


{! Oops! {+name/} above will be 'zzz' !}

Only use generic names for inline partials with the knowledge that a template later in the chain can override it.

Fork me on GitHub