htmldjangodjango-templates

Django template extension; django.template.exceptions.TemplateSyntaxError: Invalid block tag when trying to load i18n from a base template


I have a base.html template file for Django (4.1.2) as:

<!DOCTYPE html>
<html lang="en">
    {% load static %}
    {% load i18n %}
  <head>
    <meta charset="utf-8">
      {% block title %}
        <title>My Title</title>
      {% endblock %}
   
     </head>
  <body>
    {% block content %}

    {% endblock content %}
  </body>
</html>

and an index.html page, at the same level in the /templates folder of my app, extending the base one, as:

{% extends "base.html" %}

{% block content %}
  <h1>My Django project</h1>
    <ul>
      <li><a href="/admin">{% trans "Admin" %}</a></li>
      <li><a href="{% url 'foo' %}">{% trans "Foo" %}</a></li>
    </ul>
{% endblock %}

But when I browse the latter page, the server returns the following error:

django.template.exceptions.TemplateSyntaxError:
  Invalid block tag on line 6:
    'trans', expected 'endblock'.
    Did you forget to register or load this tag?

But if I simply add {% load i18n %} at the second line of the index.html, the page loads fine.

What is wrong with the loading of the base template in the index.html page?

This doesn't help as it doesn't differentiate the behaviour encountered here with the fact that loading, e.g. {% load django_bootstrap5 %} in base.html is working very well through all child pages without having to ever specify it again in those pages.


Solution

  • I found a way to globally enable i18n in settings.py:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                # ... some options here ...
                'builtins': ['django.templatetags.i18n'], # <---- add this line
            },
        },
    ]
    

    Then, apparently, you no more need to load this template tag in every html template. It is not even necessary in base.html anymore.

    More on templates built-in backends: https://docs.djangoproject.com/en/4.1/topics/templates/#module-django.template.backends.django

    And on writing {% load i18n %} only once: https://code.djangoproject.com/ticket/1193

    Inspired by: Load a Django template tag library for all views by default