This article example describes the inheritance operation of static templates under the Django framework. Shared for your reference, as follows:
Foreword: First blog, with graduation school recruitment just around the corner, I took the time to organize all the projects I've done.
Development environment: python3.4, django1.8
Beginning python and django to do the project, encountered a lot of front-end page code redundancy, especially the head and footer, the code is the same. At first, the code has been copy and paste, and then found that Django comes with a template inheritance is very good. I am a novice, only published personal experience, do feel very useful. Welcome to guide you.
①. Define a base template, which is later inherited by sub-templates.
Named , this page mainly puts the public part of the code, each sub-page can inherit the style of this page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}home page (of a website){% endblock %}</title> {% block js %} {% endblock %} {% block css %} {% endblock %} </head> <body> {% block content %}{% endblock %} </body> </html>
②. Write the individual sub-templates.
As shown below, {% extends '' %} is used as the base template and must be placed on the first line to be recognized.
The {% block %} tag tells the template engine that sub-templates can overload these
{% include %} Allows other templates to be included in the template.
Note that static files such as css and js are recognized differently than html.
{% extends '' %} <!-- This page is not allowedjsas well ascsscoding,contentcoding可直接写在本文件中,Here's justcontent的实例coding --> {% block title %} <!-- Write the page title here --> {% endblock %} {% block js %} <!-- Fill herejslink (on a website) --> <script type="text/javascript" src="..."></script> {% endblock %} {% block css %} <!-- Fill herecsslink (on a website) --> {% endblock %} {% block content %} <!-- Fill here页面主体内容 --> {% include 'taskApp/' %} {% endblock %}
When used in this way, not only is it easy to change, but the amount of code is obviously reduced by a lot.
I hope that what I have said in this article will help you in designing Python programs based on Django framework.