Question: Importance Of Tera Variable Assignment Location (Not Loop Related)

Please note I am behind on zola versions, mine is 0.18.0

Reproduction:

  1. zola init
  2. create content/_index.md
  3. create templates/base.html
<!doctype html>
<html>
	<body>
		{% block body %}{% endblock %}
	</body>
</html>
  1. create failing templates/index.html
{% extends "base.html" %}

{% if section %}
    {% set this = section %}
{% else %}
    {% set this = page %}
{% endif %}

{% block body %}
{{ this.content | safe }}
{% endblock %}
  1. zola serve fails:
Error: Failed to build the site
Error: Failed to render section '/home/andrew/projects/tera-bug-poc/content/_index.md'
Error: Reason: Failed to render 'index.html'
Error: Reason: Variable `this.content` not found in context while rendering 'index.html'
  1. Place if…else inside any block (this example only has a body)
  2. zola serve succeeds

I think I am just not understanding something about how Tera works here and was hoping someone could explain why “7” works. I thought variable scope might be limited to blocks, but when I have multiple blocks, I found that I could place the assignment in multiple positions and it would work, for instance, place the variable assignment in “meta” block but successfully access the variable in “body” block.

{% extends "base.html" %}

{% if section %}
    {% set this = section %}
{% else %}
    {% set this = page %}
{% endif %}

{% block body %}
{{ this.content | safe }}
{% endblock %}

When you are writing templates that are extending other templates any code outside of blocks is ignored.

You have to do:

{% extends "base.html" %}

{% block body %}

{% if section %}
    {% set this = section %}
{% else %}
    {% set this = page %}
{% endif %}

{{ this.content | safe }}
{% endblock %}

Thank you, yes that was what I meant for step 7.

I do not see this behavior mentioned in the docs.
If you would like, I can make a PR.

I’ll take a PR. It’s kind of not mentioned well either in Tera docs: Tera