_index front matter and Tera's ternary operator and optional chaining

Hi everyone, I’m trying to build a Tera template such that it attempts to read some [extra] fields from _index.md and use some default values if those fields don’t exist. I’ve tried to do this using Tera’s optional chaining and the ternary operator, but I couldn’t manage to make it work. Here’s a basic example of what I’m trying to achieve. After running zola init I create the following files:

  • content/test.md, which contains:

    +++
    template = "base.html"
    title = "I'm a title"
    [extra]
    var_1 = "I'm content"
    +++
    
  • templates/base.html, which contains:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>{{ page.title }}</h1>
    
    <p>
    This works, there's a variable called var_1:
    {{ page.extra.var_1 }}
    </p>
    
    <p>
    This also works, there's no variable called var_2, so a default value is used:
    
    {% if page.extra.var_2 %}
        {% set var_2 = page.extra.var_2 %}
    {% else %}
        {% set var_2 = "default" %}
    {% endif %}
    
    {{ var_2 }}
    </p>
    
    <p>
    Optional chaining doesn't work:
    
    {% set var_2 = page.extra.var_2? or "default" %}
    </p>
     
    <p>
    The ternary operator doesn't work either:
    
    {% set var_2 = page.extra.var_2 if page.extra.var_2 else "default" %}
    </p>
    
    </body>
    </html>
    

What I want to do is try to read var_2 from the front matter of test.md and, if it’s undefined, use a default value. When I try to achieve this using either optional chaining or the ternary operator I get similar errors:

* Failed to parse "zola_test/templates/base.html"
  --> 28:32
   |
28 | {% set var_2 = page.extra.var_2? or "default" %}
   |                                ^---
   |
   = expected `or`, `and`, `not`, `<=`, `>=`, `<`, `>`, `==`, `!=`, `+`, `-`, `*`, `/`, `%`, a filter, or `%}` or `-%}`
* Failed to parse "/home/videbar/repos/zola_test/templates/base.html"
  --> 39:33
   |
39 | {% set var_2 = page.extra.var_2 if page.extra.var_2 else "default" %}
   |                                 ^---
   |
   = expected `or`, `and`, `not`, `<=`, `>=`, `<`, `>`, `==`, `!=`, `+`, `-`, `*`, `/`, `%`, a filter, or `%}` or `-%}`

What am I doing wrong?

This will work in the next version of Zola. I need to update the current docs to say that the current version of Zola (<= 0.23) uses tera v1.

1 Like

In Tera v1, this works:

{% set var_2 = page.extra.var_2 | default(value="default") %}
1 Like

Cool, thanks a lot for the effort you put into it, I see that there’s already a remark in Zola’s documentation.