Extends tag
{% extends "skeleton.html" %}
{% block "name" %}
content
{% end %}
{% end %}
The extends
tag is used to base one template on another. This is useful for things like sites with
a common layout, CSS files, headers etc and reduces boiler plate by allowing you to define the structure or "skeleton"
of each page in a common layout.
Examples
To use extends
, you need to set up two templates. One is the "skeleton" and one is the "content"
template.
skeleton.html
<!DOCTYPE html>
<html>
<head>
<title>{% block "title" %}Page title{% end %}</title>
</head>
<body>
{% block "content" %}{% end %}
</body>
</html>
content.html
{% extends "skeleton.html" %}
{% block "title" %}Hello world{% end %}
{% block "content" %}
<p>This is the content!</p>
{% end %}
{% end %}
It would output the following:
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<body>
<p>This is the content!</p>
</body>
</html>
Things to keep in mind
Some things to keep in mind when using extends
, in no particular order:
- The {% end %} of the {% extends %} is optional (in fact, if there are any unclosed blocks at the end of a file, the processor will insert as many pseudo-{% end %} tags as necessary).
- If you put something inside the {% block %} tags in the skeleton, then the contents there will be used in case the block is not defined in the content template. This is useful for having "default" values for blocks.
- The name of the skeleton file and of the blocks is evaluated just like any other expression in Carrot. So if it's not working as you expect, it could be that you've forgotten to put the names in quotes (this is one difference between Carrot and Jinja2).
How it works
Below is a basic description of how extends
works, which should hopefully give you some ideas about
how to make best use of it in your templates.
- When an
{% extends %}
block is encountered, all of it's children are parsed and any children that aren't themselves{% block %}
are dropped. - The blocks are added to pseudo object, named "__blocks" in the current scope.
- The template mentioned in the
{% extends %}
is parsed and rendered. - When that template is parsed, any
{% block %}
it encounters, it looks for a property with the same name in the "__blocks" variable, and if it finds one, renders it instead. If it doesn't find one, it just renders it's own content.