Django templates↓
- Create a new template file hello.html in the templates directory under the project created in the previous article. The directory structure is as follows:
HelloWorld/ |-- HelloWorld |-- manage.py `-- templates `-- hello.html
- The hello.html code is as follows:
{{hello}}
- Modify HelloWorld/settings.py and modify DIRS in TEMPLATES:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
- Modify view.py, create a new method, and bind the dictionary to the template
# -*- coding: utf-8 -*- #from django.http import HttpResponse from django.shortcuts import render def hello(request): context = {} context['hello'] = 'Hello World!' return render(request, 'hello.html', context)
- The browser accesses http://127.0.0.1:8000/hello, and the page prints out Hello World!
The following describes the tags of the Django template:
- if tag:
{% if ... %} ... {% elif ... %} ... {% else %} ... {% endif %}
The if condition accepts and , or or not keywords. - for tag:
<ul> {% for v in list %} <li>{{ v }}</li> {% endfor %} </ul> <ul> {% for v in list reversed %}{# reverse iteration#} <li>{{ v }}</li> {% endfor %} </ul>
- ifequal/ifnotequal tags:
{% ifequal value 'aaa' %} If value is equal to aaa, display the section {% else %} not equal to aaa {% endifequal%}
- Annotation tags:
{# comment#}
- include tag:
{% include "nav.html" %}
- filter:
{# to lowercase#} {{ name|lower }} {# Output the first element, and convert to uppercase#} {{ my_list|first|upper }} {# The filter can take parameters and display the first 30 words of the variable#} {{ bio|truncatewords:"30" }} {# format date object#} {{ pub_date|date:"F j, Y" }} {# Add a backslash before any backslash, single or double quotes#} {{ value|addslashes }} {# Return the length of the variable#} {{ value|length }}
- Template inheritance:
<p>The first line, the fixed part. </p> {% block main %} block is the part replaced by the inheritor {% endblock %}
{% extends "base.html" %} {% block main %} replaced {% endblock %}
The end result is:The first line, the fixed part. replaced
This chapter is written here first!