Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Django's template extends variable?

The django template doc mentions the following for extending templates:

{% extends variable %}

Where do I define the variable? Is it from the views.py?

like image 633
Thierry Lam Avatar asked Aug 25 '09 21:08

Thierry Lam


People also ask

How do I use extends in Django template?

Using the extends tag in Django requires several things. (1) First, you need a Django template to extend. This is the template whose base code you want to use for other templates. (2) Next, you need to add the Django extend block content tags where each of the other templates will be loaded in.

What is the use of Extends template tag reference?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.

How do you pass variables from Django view to a template?

Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.


2 Answers

{% extends %} actually takes a string - the location of the template to extend.

If you want to declare this variable in Python, pass it in to the template loader using your dictionary. Example:

import django.http
from django.shortcuts import render_to_response
# ...
INDEX_EXTEND = "index.html"
# ...
def response(request) :
    return render_to_response("myview.html", {'extend': INDEX_EXTEND})

And then in the view:

{% extends extend %}

Notice that 'extend' was passed in the dictionary passed to the template. You can of course define the variable anywhere else in your .py file - or even in the dictionary declaration itself.

Remember that {% extends %} can also be invoked as such:

{% extends "index.html" %}

Check out the docs on Template inheritance, too.

like image 71
Lucas Jones Avatar answered Oct 08 '22 00:10

Lucas Jones


Yes, it's just a context variable like any other.

You don't need to use a variable - {% extends "main.html" %} is perfectly acceptable, in fact preferable unless you need to do something massively dynamic with template inheritance.

like image 30
Daniel Roseman Avatar answered Oct 07 '22 23:10

Daniel Roseman