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?
The most flexible way to reuse template fragments is to define an inclusion_tag. You can pass arguments to your custom tag, process them a bit in Python, then bounce back to a template. Direct inclusion only works for fragments that don't depend on the surrounding context.
{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
Use Django extends in multiple templates Note that you can extend the header. html to multiple HTML documents using the same document structure and DTL block content tags. This means the header can render in multiple templates. The example above extends the header template to a new HTML template called contact.
Snippets are stand-alone, re-usable code pieces that can add additional functionality. An HTML snippet is a small portion of source code in HTML. They can be used to build different elements (like a list view, different styled buttons, text display, customized search bar and so on). Add an HTML snippet.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With