Adding a tags page to your Zola blog

published:

tags: [ #zola ]

UPDATE: So it looks like Zola provides a <domain>/tags/ page by default which can be disabled by passing in render = false to the taxonomies config taxonomies = [{ name = "tags", render = false }]. But the instructions below are still helpful for adding a custom listing page.

I was recently looking to add a tags page to the current blog based on Zola. The docs talk about taxonomies and how to use them. Tags are a kind of taxonomy that we can enable by setting this in zola.toml:

taxonomies = [{ name = "tags" }]                     # Enable tags taxonomy

and then enabling them in each post in the header toml section as:

+++
title = "Shape of water"
date = 2019-08-15
[taxonomies]
tags = ["movie", "faves"]
+++

But, this does not give you a way to view all of the tags in a single page, so that you can find the posts associated with each.

I found someone else who had the same issue and shared their solution in this write up. That got me experimenting a bit. I made some small uupdates to the page itself, but the final solution is pretty close to what was suggested.

The main idea was to define a tags.html which allows you to pull the tags via the get_taxonomy(kind="tags") function in the template and iterating over the resulting list.

A note on the internals

We see in Zola that it registers a tera function here as:

    site.tera.register_function(
        "get_taxonomy",
        functions::GetTaxonomy::new(&site.config.default_language, site.cache.clone()),
    );

This function is then implemented by Zola as:

impl Function<TeraResult<Value>> for GetTaxonomy {
    fn call(&self, kwargs: Kwargs, state: &State) -> TeraResult<Value> {
        let kind: &str = kwargs.must_get("kind")?;
        let required: bool = kwargs.get("required")?.unwrap_or(true);
        let lang: String =
            kwargs.get("lang")?.or(state.get("lang")?).unwrap_or_else(|| self.default_lang.clone());

        match self.cache.get_taxonomy(&lang, kind) {
            Some(cached) => Ok(cached.value.clone()),
            None if !required => Ok(Value::none()),
            None => Err(Error::message(format!(
                "`get_taxonomy` received an unknown taxonomy as kind: {}",
                kind
            ))),
        }
    }
}

There is some caching optimization going on here, since the underlying cache member is of the interface:

/// All pre-serialized data for template rendering.
#[derive(Debug, Clone, Default)]
pub struct RenderCache {
    pub pages: AHashMap<PathBuf, CachedContent>,
    pub sections: AHashMap<PathBuf, CachedContent>,
    /// canonical path -> (lang -> file path)
    pub pages_by_canonical: AHashMap<PathBuf, AHashMap<String, PathBuf>>,
    /// canonical path -> (lang -> file path)
    pub sections_by_canonical: AHashMap<PathBuf, AHashMap<String, PathBuf>>,
    /// Serialized config per language
    pub configs: AHashMap<String, Value>,
    /// Cached taxonomies: lang -> (taxonomy_slug -> CachedTaxonomy)
    pub taxonomies: AHashMap<String, AHashMap<String, CachedTaxonomy>>,
    /// Aliases for taxos: lang -> (taxonomy name -> taxonomy slug)
    pub taxo_name_to_slug: AHashMap<String, AHashMap<String, String>>,
}

This is a type defined in tera as the following:

/// A custom Result type for this library
pub type TeraResult<T> = Result<T, Error>;