Date Tags Wagtail

While Jinja2 is based on Django templating, there are a few distinct differences. This document describes setup and customization.

1. In the Django settings file:

TEMPLATES = [
...
{
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
    'DIRS': [
        os.path.join(PROJECT_DIR, 'jinja2'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'extensions': [
            'wagtail.core.jinja2tags.core',
            'wagtail.admin.jinja2tags.userbar',
            'wagtail.images.jinja2tags.images',
        ],
        'environment': ‘myapp.jinja2.environment',
    },
}
]

Jinja templates must be placed in a jinja2/ directory in your app. The template for an EventPage model in an events app should be created at events/jinja2/events/event_page.html.

Setting the environment option gives us a place to hook in custom tags and filters.

2. jinja2.py

Django will load this module from the application directory if the Jinja2 template backend is loaded in settings.
This default example is the minimum necessary to use Django-specific tags.

from django.templatetags.static import static
from django.urls import reverse

import jinja2
from jinja2 import Environment
from jinja2.ext import Extension


def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': static,
        'url': reverse,
    })
    return env

3. Jinja support in Wagtail is explained at the Wagtail site

4. Application-specific templates go into the jinja/ directory, not the templates/ directory. For example, in an application call “apple” with a page model Pie(Page), the page template is 


Support for Wagtailmenus

Using Wagtailmenus with Jinja2 templating requires adding support for the tags main_menu and sub_menu.

In jinja2.py, add:

from wagtailmenus.templatetags.menu_tags import main_menu, sub_menu


class MenuExtension(Extension):
    def __init__(self, environment):
        super().__init__(environment)
        environment.globals.update({
            'main_menu': jinja2.contextfunction(main_menu),
            'sub_menu': jinja2.contextfunction(sub_menu),
        })