Zola Macros



Zola is a fast static site generator in a single binary with everything built-in 1 2. It uses the Tera template engine, which is similar to Jinja2, Django templates, Liquid, and Twig3.

Generic Macros

Macros are a way to reuse common parts of templates. They are similar to functions in programming languages. You can define macros in a separate file and import them in your templates. Macros can take arguments and return some HTML ref3.

Here is an example of a macro that creates a simple card component3:

Using the site structure:

 - page.html
 - macros.html
{% macro card(title, text, image) %}
<div class="card">
{% if image %}
<img src="{{ image }}" alt="{{ title }}">
{% endif %}
<div class="card-content">
<h3>{{ title }}</h3>
<p>{{ text }}</p>
{% endmacro card %}

You can save this macro in a file called macros.html and import it in your template like this:

{% import "macros-gallery.html" as macros %}

{{ macros::card(title="Zola", text="A fast static site generator", image="zola.png") }}

This will render a card with the title, text and image you provided.

You can learn more about macros and other features of Zola from its documentation3.

Macros can't really provide return values for other templates but they can be embedded in specific cases.

Image Resizing and Content Colocation

You can resize images in Zola using the built-in function resize_image, which is available in template code as well as in shortcodes. The function takes the following arguments:

The function returns an object with the following schema:

For example, to resize an image called logo.png to 200 pixels wide and 100 pixels high, you can use this code in your template:

 - imagedisplay.html


{% set resized = resize_image(path="logo.png", width=200, height=100) %}
<img src="{{ resized.url }}" alt="Logo" width="{{ resized.width }}" height="{{ resized.height }}">

You can learn more about the resize operations and how Zola performs image processing from its documentation4.

As for storing images next to the content, Zola supports assets co-location. This means that you can place any static files (such as images, CSS, JavaScript, etc.) in the same directory as your content files and they will be copied to the output directory with the same structure5. For example, if you have a page called blog/my-post.md and an image called blog/my-image.jpg, they will be copied to public/blog/my-post/index.html and public/blog/my-image.jpg, respectively.

You can access the co-located assets using the page.permalink variable, which is the full URL of a page without a trailing slash5. For example, to display an image called my-image.jpg that is co-located with a page called my-post.md, you can use this code in your template:

Direct use of an image

<img src='{{ page.permalink ~ "my-image.jpg" }}' alt="My image">

You can learn more about assets co-location and other features of Zola from its documentation5.