Search code examples
pythondjangodjango-templatesmako

Django equivalent to mako's callable blocks


Is there a Django equivalent to Mako's callable blocks?

In Mako, if I have a particular bit of HTML that I would like to reuse, I can put it in a "callable block" which can be called from multiple places in the template.

<%def name="makerow(row)">
    <tr>
    % for name in row:
        <td>${name}</td>\
    % endfor
    </tr>
</%def>

Does Django have something similar to this?


Solution

  • In Django you can include other HTML templates to accomplish this:

    {% include "main/includes/subtemplate.html" %}
    

    You can access the same variables in the included template as in the parent template from which it is included. This allows you to reuse HTML in multiple places in a template.

    An alternative is to create a custom template tag: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/ This allows you to create your own tags that generate HTML output. The Django documentation provides various examples on how to do this.