Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reuse HTML snippets in a django view

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?

like image 897
daniyalzade Avatar asked Sep 18 '10 22:09

daniyalzade


People also ask

How do I reuse a Django template?

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.

What does {% %} do in Django?

{% 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.

Can you extend more than one template Django?

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.

What are HTML snippets?

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.


2 Answers

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.

like image 179
Sam Dolan Avatar answered Sep 18 '22 19:09

Sam Dolan


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

like image 24
gitaarik Avatar answered Sep 19 '22 19:09

gitaarik