Snippets and includes are the main tools to organize the code of a theme. While snippets define reusable blocks of code within a template, includes allow for splitting templates into multiple files. Together they form the basis for inheritance and recursion.
Snippets
The snippet statement defines a reusable block of code. To use a snippet, it is enough to wrap its name in statement delimiters. A snippet always inherits the context of the code that calls it.
<# Define a snippet with the name "card". #>
<@ snippet card @>
<div class="card">
<a href="@{ url }">@{ title }</a>
</div>
<@ end @>
<# Use the snippet for each page in the pagelist. #>
<@ foreach in pagelist @>
<@ card @>
<@ end @>
Snippet names can contain letters, numbers, underscores and dashes. Since snippets share the statement syntax with functions and take precedence over them, avoid names of built-in functions.
Overriding Snippets
All snippet definitions of a template are collected before the template is actually rendered. In case a snippet is defined multiple times, the last definition wins. That also means that a snippet can be called before it is defined and that snippets that are defined in an included file can be overridden afterwards. This is the basic principle of inheritance in Automad.
<@ snippet greeting @>Hello!<@ end @>
<@ greeting @>
<@ snippet greeting @>Hi there!<@ end @>
<# The rendered output is "Hi there!" #>
Recursion
Snippets can also call themselves. That makes them the perfect tool for rendering nested structures like site trees. Learn more about building recursive navigations.
Includes
In most cases, multiple templates of a theme share recurring elements, such as a header, a navbar or a footer. Those elements can be stored in separate files and included wherever they are needed. In order to include a file, simply wrap its path in statement delimiters:
<@ components/header.php @>
The file path is always relative to the including file, also in case the including file is itself included by another file. Included files are processed within the current context and can use all variables, snippets and collections just like the including template. Variables that are used in included files are also detected by the dashboard and show up as fields in the page settings.
Organizing Components
A common pattern, which is also used by the Standard Lite theme, is to keep every component in its own file inside a components directory. Each component wraps its markup in a snippet and calls it right away. That way, a component renders as soon as it is included, while its snippet can still be overridden by a derived template.
<# components/main.php #>
<@~ snippet main ~@>
<main class="content">
@{ +main }
</main>
<@~ end ~@>
<@ main @>
A layout component can then put all components together:
<# components/layout.php #>
<@~ snippet layout ~@>
<div class="layout">
<@ navbar.php @>
<@ title.php @>
<@ main.php @>
<@ footer.php @>
</div>
<@~ end ~@>
<@ layout @>