Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a reusable template in Django?

Tags:

What is the Django way of creating a reusable template?

Example: Suppose a lot of my pages contain a "Latest News" box and following the DRY principle, I would like to define it once and reuse it in the other pages. How would I do this with Django (or Jinja2) templates?

Reading through Django's Template Documentation I get the impression that Django templates offer "top-down" inheritance where the sub-template itself determines in which super-template it is going to be embedded:

<!-- Super-template (not valid, for illustration): --> <html>   <head><title>Title</title></head>   <body>{% block content %}{% endblock %}</body> </html> 
<!-- Sub-template: --> {% extends "base.html" %} {% block content %} <div class="latest-news">News</div> {% endblock %} 

So what is the technique to reuse a block (a sub-template) in several places?

like image 279
Hbf Avatar asked Feb 27 '12 20:02

Hbf


People also ask

Do Django templates have multiple extends?

Yes you can extend different or same templates.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How do I add a template to Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What is Jinja pattern in Django?

Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as source code. Jinja.


1 Answers

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.

Quick example from the docs:

In app/templatetags/poll_extras.py register the tag with a decoration:

from django import template register = template.Library()  @register.inclusion_tag('results.html') def show_results(poll):     choices = poll.choice_set.all()     return {'choices': choices} 

In app/templates/results.html:

<ul> {% for choice in choices %}     <li> {{ choice }} </li> {% endfor %} </ul> 

Calling the tag:

{% load poll_extras %} {% show_results poll %} 
like image 69
Tobu Avatar answered Oct 23 '22 09:10

Tobu