Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Django template


May 14, 2021 Django


Table of contents


Django Template Introduction

In the Django framework, templates are tools that help developers quickly build pages that are presented to users. F or writing html code, you can also embed template code conversion more convenient to complete page development, and then by rendering the template in the view, the design of the generated template to achieve the separation of business logic view and display content template, a view can use any one template, a template can be used by multiple views.

Note: The currently displayed page is the template and the data

The template is divided into two parts:

  • Static pages: Mainly includes CSS, HTML, JS, pictures
  • Dynamic fill: Mainly through the template language to dynamically produce some of the content on the page

The use of template files

Typically, html pages are generated dynamically through the template language in a view function, and then the contents of the page are returned to the client for display.

  1. Load the template file loader.get_template, get the contents of the template file, and produce a template object
  2. Define the template for other RequestContexts to pass data to the template file
  3. The template file renders the html page content rendered, replacing the corresponding variables with the passed data, resulting in a replaced html content in the table

from django.shortcuts import render
from django.template import loader,RequestContext
from django.http import HttpResponse
# Create your views here.
def my_render(request,template_path,context={}):
  # 1.加载模板文件,获取一个模板对象
  temp = loader.get_template(template_path)
  # 2.定义模板上下文,给模板传递数据
  context = RequestContext(request, context)
  # 3.模板渲染,产生一个替换后的html内容
  res_html = temp.render(context)
  # 4.返回应答
  return HttpResponse(res_html)
# /index
def index(request):
  # return my_render(request,'booktest/index.html') 这是自己封装的render
  # 其实Django已经封装好了,可以直接使用
  return render(request,'booktest/index.html')

The order in which the template files are loaded

  1. First go below the directory of the configured current template
  2. If you don't have one under the configured directory, go to the app file you've created to find the template file (this way, only if the app must have a template folder below)

Django template

The template language

  1. The template language (Django template language) is short for DTL.
  2. The template variable

The template variable name consists of numbers, letters, underscores, and points

Note: You cannot start with the following dashes

3. Template label

{% 代码段 %}
#for循环:
#遍历列表:
{% for i in 列表 %}
#列表不为空时执行
{% empty %}
#列表为空时执行
{% endfor %}
#若加上关键字reversed则倒序遍历:
{% for x in 列表 reversed %} {% endfor %} #在for循环中可以通过{{ forloop.counter }}得到for循环遍历到几次 #判断语句: {% if %} {% elif %} {% else %} {% endif %}            

4. Relationship comparison operator

> <> = <= ==! =

Notice: When using the relationship, the operator is compared, there must be space on both sides

5. Logical operations

Don't

Filter

  • Filters are used to manipulate template variables
  • Use:

> Add: Add a value of 2.Use form: {{Value | Add: "2"}}

> CUT: Remove all Arg's values from a given value.Use form: {{Value | Cut: arg}}

> Date: Format Time Format.Use form: {{value | Date: "YMD H: M: s"}}

> Category: If Value is false, then the output uses a recombination value.Use form: {{Value | Alternative value: "Nothing"}}.For example, if the value is "", then the output will be Nothing

> first: Returns the first element in the list / string.Use form: {{Value | first}}

> Length: The length of the return value is returned.Use form: {{Value | length}}

To customize a filter:

  • Create a new python package called a template label under your own app file
  • Create a new py file for a filter in the python package
  • Configuration
from django import template#导入模块
register = template.Library() #标准语句都不能改
#写函数装饰器
@register.filter
def add_xx(value, arg):  # 最多有两个
return '{}-{}'.format(value, arg)#返回两个值的拼接
#在html使用方式
{% load my_tags %}#引用模块
{{ 'alex'|add_xx:'dsb' }}#通过函数名使用
@register.filter(name = xxx)#可以直接通过name等于的xxx取引用
def add_xx(value, arg):  # 最多有两个
return '{}-{}'.format(value, arg)#返回两个值的拼接
#在html使用方式
{% load my_tags %}#引用模块
{{'alex'|xxx:'dsb'}}#通过赋值的name引用

The template comment

  • One-line Comments: # 注释.
  • Multi-line comments: s%comment%?
  • The content of the comment
  • %Final Comment %"
  • The content browser of the template comment can not see, and the content browser of the html comment can see the comment of html:

The inheritance of the template

The template is written at the beginning of the template, at the end of the "%endblock%", which indicates that you can be inherited

For example, the following new demo .html:

1. Parent template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        h1{
            color: blue;
        }
    </style>
</head>
<body>
{% block demo %}
<h1>模板1</h1>
{% endblock %}

{% block demo1 %}
<h1>模板2</h1>
{% endblock %}

{% block demo2 %}
<h1>模板3</h1>
{% endblock %}

{% block demo3 %}
<h1 style="color: red">模板4</h1>
{% endblock %}

{% block demo4 %}
<h1>模板5</h1>
{% endblock %}

</body>
</html>

2. Sub-templates

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% extends 'demo.html' %} #继承模板

{% block demo %} #对引入的模板块进行从写
    <h1>这里是重写</h1>
{% endblock %}
</body>
</html>

Module appointments are complete, and you can see that the effect is as follows:

Django template