Xiao Bian recently learned template inheritance and custom filters.
Template inheritance
Django template engine is the most powerful and most complex part of the template is inherited. Template inheritance allows you to create a basic "skeleton" template that contains all the elements of your site, and you can define templates quilt blocks can covered.
base.html this page as a template inherit indexxx.html inheritance and references cited ss.html this page as a template in the template.
base.html code is as follows: as a skeleton a template. Dug three pits, content, title, demo.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}this title{% endblock %}</title> </head> <body> {% load rand %} {% block content %} This is content {% endblock %}<br> {% block demo %} this is Demo {% endblock %} <br> { This is an advertisement}% AD% Block { Ah ha ha ha% endblock %} </body> </html>
indexText.html:
Red marked portion is outside the block.
When we opened the path to the child template, something sub-template block contains overwrite thing is the same name as the parent template block contains. If there is something no parent template template quilt cover, as described above parent template text. Then display the contents of the parent template called text block will be inherited to the child template.
(Content does not appear after the red part of the browser to open) visible indexText.html Africa inherited block can not be displayed.
<!DOCTYPE html> <html lang="en"> {% extends 'student/base.html' %} {% block title %} hello world{% endblock %} {% block content %}噜啦啦{{ block.super }} {% endblock %} {% load rand %} <body> {% block demo %}This is indexDemo {% include 'student/ss.html' %}{% endblock %} <br> {% block ad %} index 广告 eeeeee {{ block.super }} {% endblock %} {% block rand %} this is rand function {% endblock %} 大家好!! </body>
Custom filter
* In the project directory, create a python package called the common
* added to the common settings file installed_app
* Create custom filters and tags files in common directory inside templatetags
* You can also create templatetags within the app
templatetags folder to store custom templates and tags.
FIG as rand.py - defined filters
from django.template import Library register = Library() def mycut(value,arg): return value.replace(arg,'') register.filter('mycut',mycut)
The filter as defined in base.html into:
{% load rand %}
<h1>{{ 'lhgfdaaaafgh' | mycut:'a' }}</h1> <h1>{{ tn | mycut:'a' }}</h1>
Write a custom filter method decorators:
Decorator:
def funa(fun): def funb(a): print(111) print(a) fun() return funb @funa def func(): print(2222) func(333)
Output:
333
2222
Funb
Registered in the rand.py
@register.filter(name='mylower') def mylower(value): return value.lower()
base.html:
<h1>{{ 'ASSSS' | mylower }}</h1>
Results in Text
Benseghir