Reputation: 991
I am working on a django project (my first), and in one of my views, I have a sophisticated html snippet with JS weaved within it. I would like to reuse this "component" somewhere else in the same view. Is there a way of achieving this? Please let me know if this design is faulty to begin with?
Upvotes: 20
Views: 14669
Reputation: 46300
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" %}
Upvotes: 10
Reputation: 53850
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.
Upvotes: 1
Reputation: 32532
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.
Upvotes: 25
Reputation: 188034
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.
Upvotes: 2