Useful Template Snippets
Find below a collection of useful snippets for common tasks using Automad's template language.
Content
Defining a default value in case a variable is empty:
@{ text | def ('Hello there') }
Shorten a text to 100 chars:
@{ text | 100 }
Finding the first paragraph in a variable to be used in a page preview card or similar:
<# Markdown variable #>
@{ text | markdown | findFirstParagraph }
<# Blocks #>
@{ +main | findFirstParagraph }
Getting the src
of the first image in a variable to be used in a page card:
<# Markdown variable #>
@{ text | markdown | findFirstImage }
<# Blocks #>
@{ +main | findFirstImage }
For example within a pagelist loop:
<@ foreach in pagelist @>
<@ set { :img: @{ +main | findFirstImage } }
<@ if @{ :img } @>
<img src="@{ :img }">
<@ end @>
<@ end @>
Loops
Looping over a list of files with resizing and cropping:
<@ foreach in "*.png, *.jpg" { width: 400, height: 400, crop: true } @>
<img src="@{ :fileResized }" alt="@{ :basename }">
<@ end @>
Create a recursive navigation tree:
<# Create snippet to be used recursively #>
<@ snippet tree @>
<# Only show children/siblings in current path #>
<@~ if @{ :currentPath } @>
<# Only create new list in case the current context has children #>
<@~ if @{ :pagelistCount } @>
<ul>
<@~ foreach in pagelist @>
<li<@ if @{ :current } @> class="active"<@ end @>>
<a href="@{ url }">@{ title | stripTags }</a>
<# Call tree snippet recursively #>
<@~ tree ~@>
</li>
<@~ end @>
</ul>
<@~ end @>
<@~ end @>
<@~ end ~@>
<# Create new pagelist including all children adapting to the current context. #>
<@~ newPagelist { type: 'children' } ~@>
<# Change context to the homepage #>
<@~ with "/" @>
<# Call recursive tree snippet #>
<@~ tree @>
<@~ end @>
Looping over page tags to create a comma separate list of tags with links to the parent page:
<@~ foreach in tags ~@>
<@~ if @{ :i } > 1 @>, <@ end ~@>
<a href="@{ :parent }?filter=@{ :tag }">@{ :tag }</a>
<@~ end ~@>