Inheritance of Django templates, django templates
When using djangofor webdevelopment, a basic framework template base.html will be constructed in the past, and then the common parts and definition blocks of the websites it contains will be reloaded in its subtemplates.
First, create a base.html file. The source code is:
<!DOCTYPE html>This base.html template defines a simple html framework document, which will be used on pages on our site. The role of a sub-template is to overload and add
Or keep the content of those blocks.
Now we create a new current_datetime.html template to use it:
{% extends "base.html" %}{% block title %}The current time{% endblock %}{% block content %}<p>It is now {{current_date }}.</p>{% endblock %}
Create another hours_ahead.html template. The source code is:
{% extends "base.html" %}{% block title %}Future time{% endblock %}{% block content %}<p>In {{hour_offset }} hour(s),it will be {{next_time}}.</p>{% endblock %}
The preceding non-html tags will be explained again. Now two new functions, index4, and index5, are created in views. py, which correspond to the two templates respectively. Source code:
def index4(req,offset): offset=int(offset) next_time=datetime.datetime.now()+datetime.timedelta(hours=offset) return render_to_response("hours_ahead.html",{'hour_offset':offset,'next_time':next_time})def index5(req): now=datetime.datetime.now() return render_to_response('current_datetime.html',{'current_date':now})
The configuration in the url is as follows:
url(r'^hours_ahead/(\d{1,2}$)','blog.views.index4'), url(r'^current_datetime/$','blog.views.index5'),
Now the server is started, and the effect is in the browser. current_datetime.html is:
The effect in hours_ahead.html is:
As shown in the following figure, the role played by base.html is also interpreted. Both html uses the {% extends %} tag,
When using {% block XXXXX % }{% endblock1_limit, the content in base.html inherits the content of the base.html tag.
Therefore, code redundancy is greatly avoided. Each template only contains its own unique code and does not need to be redundant. If you want to make site-level design changes, you only need
Modify base.html. All other templates immediately reflect the modifications.
This document describes how to use the base.html template for the inheritance of django.