Blocks in views

The main way to make a view more modular is by using {{block ...}}s and this mechanism is an alternative to the mechanism discussed in the previous section.

To understand how this works, consider apps based on the scaffolding app welcome, which has a view layout.html. This view is extended by the view default/index.html via {{extend 'layout.html'}}. The contents of layout.html predefine certain blocks with certain default content, and these are therefore included into default/index.html.

You can override these default content blocks by enclosing your new content inside the same block name. The location of the block in the layout.html is not changed, but the contents is.

Here is a simplifed version. Imagine this is “layout.html”:

  1. <html>
  2. <body>
  3. {{include}}
  4. <div class="sidebar">
  5. {{block mysidebar}}
  6. my default sidebar (this content to be replaced)
  7. {{end}}
  8. </div>
  9. </body>
  10. </html>

and this is a simple extending view default/index.html:

  1. {{extend 'layout.html'}}
  2. Hello World!!!
  3. {{block mysidebar}}
  4. my new sidebar!!!
  5. {{end}}

It generates the following output, where the content is provided by the over-riding block in the extending view, yet the enclosing DIV and class comes from layout.html. This allows consistency across views:

  1. <html>
  2. <body>
  3. Hello World!!!
  4. <div class="sidebar">
  5. my new sidebar!!!
  6. </div>
  7. </body>
  8. </html>

The real layout.html defines a number of useful blocks, and you can easily add more to match the layout your desire.

You can have many blocks, and if a block is present in the extended view but not in the extending view, the content of the extended view is used. Also, notice that unlike with functions, it is not necessary to define blocks before the {{extend ...}} — even if defined after the extend, they can be used to make substitutions anywhere in the extended view.

Inside a block, you can use the expression {{super}} to include the content of the parent. For example, if we replace the above extending view with:

  1. {{extend 'layout.html'}}
  2. Hello World!!!
  3. {{block mysidebar}}
  4. {{super}}
  5. my new sidebar!!!
  6. {{end}}

we get:

  1. <html>
  2. <body>
  3. Hello World!!!
  4. <div class="sidebar">
  5. my default sidebar
  6. my new sidebar!
  7. </div>
  8. </body>
  9. </html>