Required template blocks

@adamchainz suggested I make a post here, so here we are.

The idea is to have an optional required parameter for the {% block %} tag:

{# base.html #}
{% block title required %}{% endblock %}

{# home.html #}
{% extends "base.html" %}

This would throw some kind of error in the second template, if you forget to override the required block.

Based on this tip I wrote.

I very briefly looked into this, it should be possible with some small changes to BlockNode and / or do_block(), but I’m not super familiar with template blocks and I didn’t think about it very hard yet.

3 Likes

Yes… per my Mastodon post, I’m in favour. It’s a small but real problem. I’ve seen a few cases where a page was missing a title or other metadata because the relevant block was missed.

I think this is a great idea. I saw Adam’s post on Mastodon and realised this was a common problem I had encountered but didn’t have a good solution to fix it. The custom template tag is a good solution, but would be great to have this as an option in core Django. Of course, the docs will need to make sure people understand that if they choose to use this tag, they must have good testing for all views, otherwise their sites will break in production.

I read Tom’s tip last night and added the template tag to a project to feel out. I’m +0 because it feels useful.

I would be +1 if the template syntax were required=(True|False) versus a syntax where something happens based on including the parameter’s name. That might also help to establish a strict mode for projects that want to pass in a variable to get there over time.

I also think this is a good candidate to be added to Django core, though while talking about this feature with Jeff he did raise a good question: how would block nesting work? That is, there is a non-required block which defines inside of it required blocks.

1 Like

I’m +1

If I understood correctly we want add in the Djangot template what it’s already in Jinja ?
https://jinja.palletsprojects.com/en/3.1.x/templates/#required-blocks