How do I check if a block has a value in the Tera templating engine used by Zola?

216 Views Asked by At

I have a title like this in my Zola (which uses the Tera templating engine) website:

<title>{% block title %}{% endblock %} - Newbyte's blog</title>

This generates something like this:

<title>Birds around the world - Newbyte's blog</title>

However, if I don't specify a title in a subtemplate, it generates this:

<title> - Newbyte's blog</title>

I would like to omit the " - " part if there's no title specified any only generate this

<title>Newbyte's blog</title>

Is there any way to achieve this in the Tera templating engine? I tried doing this, but it doesn't seem to work. It never generates the " - " part:

<title>{% block title %}{% if title %} - {% endif %}{% endblock %}Newbyte's blog</title>
1

There are 1 best solutions below

2
On

i know that in jinja2 you can check if a block is empty by calling self.block_name(), but id does not work on zola.

but, i know how to achieve what you want (the title thing).

first, define the title of your page in config.toml, on the title key (or another, if you wish). Here's an example of the file:

base_url = "https://blog.dpanovitch.dev"
# this will be the prefix/suffix of the title of all pages
title = "Personal Blog"
description = "Site's description"
default_language = "en"
output_dir = "public"
compile_sass = false

then, place the following template on your root html.

{% if page and page.title %}
  {% set title = page.title ~ ' - ' ~ config.title %}
{% else %}
  {% set title = config.title %}
{% endif %}

<title>
  {{ title }}
</title>

basically, it checks if the current page (a post, for example) that its rendering has a title defined on the frontmatter. if it does, it sets a variable called title to {page.title} - {config.title}.

if it does not have that variable, it will use the title defined on your config.toml

then, it uses that variable inside the <title> tag.

note that this means that you only need to set the page title on the front matter of a markdown file, and not using the block title.