Sometimes while you’re building a site using Django you may notice that you’re repeating the same chunk of HTML over and over again on different pages. Depending on the complexity of the HTML, that could create a maintenance nightmare. In this example I’m going to show how you can wrap up that HTML block and reuse it without repeating it using a custom block template tag.
The goal in this example is to build a sort of sub-template that can be reused on any template page. In some cases it may be sufficient to have a snippet that is added to another template using the {% include %}
block, but since what you can pass into that block is so limited we’ll sometimes need to roll our own.

Image credit: Vanessa Bucceri via Unsplash.
Block tags differ from regular template tags because in order to invoke them you have to use at least 2 tags (a beginning and an end) and any code you put between them can be interpreted and altered by the tags. You’re probably familiar with block tags such as {% block %}{% endblock %}
, {% for %}{% endfor %}
, and {% if %}{% endif %}
.
In this example we’ll create a template tag that will auto-generate all of the HTML necessary to display a Bootstrap modal using custom template block tags {% modal %}
and {% endmodal %}
.