How do I reuse HTML snippets in a django view

Not sure, if you like to reuse your HTML in different templates (rendered by different views). If so, look into Django's template inheritance mechanism:

The most powerful -- and thus the most complex -- part of Django's template engine is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.


Use the {% include '/my/common/template.html' %} templatetag.

Loads a template and renders it with the current context. This is a way of "including" other templates within a template.

The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.


I know it's an old one but maybe someone is gonna have use of this answer.

There's also the inclusion tag. It's like the include tag, only you can pass it arguments and process it as a seperate template.

Put this in my_app/templatetags/my_templatetags.py:

@register.inclusion_tag('my_snippet.html')
def my_snippet(url, title):
    return {'url': url, 'title': title}

and then my_snippet.html can be:

<a href="{{ url }}">{{ title }}</a>

then, to use this snippet in your templates:

{% load my_templatetags %}
{% my_snippet "/homepage/" "Homepage" %}

More info: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags