[Django]-How do I reuse HTML snippets in a django view

24👍

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.

9👍

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

2👍

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.

👤miku

1👍

You should try Django custom template tags. This way you will keep your snippets in an external file and then call them easily by something like {{ your_custom_tag }}. It’s a very convenient method for working with reusable chunks of xhtml markup. You can even use arguments with these custom tags, something like {{ your_custom_tag|image:"logo.png" }}.
You can learn more about custom tags here.

Leave a comment