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”:
<html>
<body>
{{include}}
<div class="sidebar">
{{block mysidebar}}
my default sidebar (this content to be replaced)
{{end}}
</div>
</body>
</html>
and this is a simple extending view default/index.html
:
{{extend 'layout.html'}}
Hello World!!!
{{block mysidebar}}
my new sidebar!!!
{{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:
<html>
<body>
Hello World!!!
<div class="sidebar">
my new sidebar!!!
</div>
</body>
</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:
{{extend 'layout.html'}}
Hello World!!!
{{block mysidebar}}
{{super}}
my new sidebar!!!
{{end}}
we get:
<html>
<body>
Hello World!!!
<div class="sidebar">
my default sidebar
my new sidebar!
</div>
</body>
</html>