Template Variables and Template Filters

Keywords: Python Django Attribute IE

1 Template Path Configuration and Search

Template paths are configured in settings.py of configuration files in two ways:

  1. DIRS defines a list of directories, which the template engine searches in list order to find template source files. The templates folder is under the project and directory.
  2. APP_DIRS informs the template engine whether it should go into each installed application to find the template. If the value is True, the template will go to the Templates folder under the registered app to find the template. So we can also create template directory templates to store templates in each app. This way, we need to add this app to the INSTALLED_APPS list of the set.py file.

Among them, the first mode has a high priority. Template engine will search the template file in the first mode first, and search the template file in the second mode only if it does not exist. The engine will return as soon as it finds the template that meets the requirements.

2 Template Variables

  • Template variable usage rules
  1. Syntax: {{{variable name}}
  2. Variable names consist of letters, numbers, and underscores. They must not have spaces and punctuation marks, and cannot begin with underscores.
  3. You can use dictionaries, lists, functions, models, methods
  4. Do not rename with python or Django keywords
  5. Variables and lookups
  • Where a point (.) is encountered, the following order is used to find it:
  1. Dictionary key value lookup
  2. Attribute or method lookup
  3. Digital index lookup

If the result is callable, the call takes no parameters and the value of the template is the result of the call.

If rendering fails, it returns null (')

3 template filter

  • Effect

Filter variables. Before the real rendering, the filter will process the variables according to the function, and then replace the original variables to show the results.

Grammar: {{fruits|lower}}

  • Chain use

Pipeline symbols are called in chains, such as a function of converting all characters into lowercase and the first character into uppercase.

Grammar: {fruits|lower|capfirst}

  • Using parameters

Filters can use parameters, colons after filter names: "Add parameters, such as to remove all spaces in a string, you can use cut filters.

Grammar: {fruits|cut: "}}}

When using parameters, there must be no spaces between colons and parameters, and they must be next to each other.

  • Common filters
Filter Effect
add Strings, numbers, and lists are added, and if they fail, they are returned empty.
default If the variable resolution fails, use the given default value. Including empty "" and None
first Returns the first value
last Returns the last value
date Formatting time and date
time Formatting time
join Connection string list
length Returns the length of a string, list, or array
length_is To determine whether the length of the target variable is a specified value, return True or Flase
lower All lowercase letters
upper small-caps
truncatechars To truncate a character according to a subsequent given parameter, the excess is represented by..
truncatewords Ibid., but in words
capfirst title case
slice Cut lists in the same way as python slices
striptags Remove all html tags
safe Automatic escaping of closed variables
floatformat Floating-point formatting
 
  • date and time filter formats
format Effect
Y Four-digit years, such as 2018
y Two-digit years, such as: 18
m Two-digit months, such as: 01,09
n One-digit months, such as: 1, 9, 12
d Two-digit days, e.g. 01, 09, 31
j One-digit days, such as: 1, 9, 31
g A 12-hour one-digit hour, e.g. 1,9,12
G A 24-hour one-digit hour, e.g. 0, 8, 23
h Double-digit hours in the 12-hour system, e.g. 01, 09, 12
H 24-hour double-digit hours, e.g. 01, 13, 24
i Minutes, from 00-59
s Second, from 00-59
 
  • Example
 1 # student Lower views.py
 2 from django.http import HttpResponse
 3 from django.shortcuts import render, reverse, redirect
 4 from datetime import datetime
 5 
 6 def hello(request):
 7     current_time = datetime.now()
 8     lt = [1, 'l', 66]
 9     li = ['p']
10     dt = {'tt': 55, 'age': 10}
11     tl = ('l', 4, 99)
12 
13     def func():
14         return 'hello'
15 
16     class Car:
17         def __init__(self, brand, price):
18             self.brand = brand
19             self.price = price
20 
21         @staticmethod
22         def travel(self):
23             print('ssssss')
24             return 'sou~~~'
25     s_car = Car('ferrari', 1)
26     return render(request, 'student/index.html',
27                   context={
28                       'current_time': current_time,
29                       'lt': lt,
30                       'li': li,
31                       'dt': dt,
32                       'tl': tl,
33                       'func': func,
34                       'car': s_car,
35                       'travle': s_car.travel,
36                   })
 1 {#Corresponding index.html#}
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Student</title>
 7 </head>
 8 <body>
 9     <h1>Here is the student's homepage.</h1>
10     <form action="">
11         <h1>Current time:{{ current_time|date:'Y-m-d H:i:s' }}</h1>
12         <h2>This is a list:{{ lt|add:li }}</h2>
13         <h2>This is a slice of the list:{{ lt|slice:":2" }}</h2>
14         <h2>list{{ lt }}The length is:{{ lt|length }}</h2>
15         <h2>list{{ lt }}The length is{{ lt|length }}Do you:{{ lt|length_is:3 }}</h2>
16         <h2>This is a dictionary:{{ dt }}</h2>
17         <h2>This is a tuple:{{ tl }}</h2>
18         <h2>This is the first value of the tuple:{{ tl|first }}</h2>
19         <h2>This is the last value of the tuple:{{ tl|last }}</h2>
20         <h2>This is a value of the list:{{ lt.0|add:5 }}</h2>
21         <h2>This is a function:{{ func|capfirst }}</h2>
22         <h2>This is a class object:{{ car }}</h2>
23         <h2>This is a class object property:{{ car.brand }}</h2>
24         <h2>This is a class object method:{{ travel|default:"nothing"|add:' haha'|title }}</h2>
25         <p>User name:<input type="text"></p>
26         <p>Password:<input type="password"></p>
27         <p><input type="submit" value="Sign in"></p>
28     </form>
29 </body>
30 </html>

Final effect

4 automatic escape

Automatic escape is to convert some special characters of variables, such as left arrow (<), right arrow (>) into html code, in order to deal with some unsafe variables.

Before escape After escape
< &lt;
> &gt;
' &#39;
" &quot;
& &amp;
 

5 References to static files

  • Create a static directory under the project directory, and create a css, image, and JS directory to distinguish different types of files.
  • Add STATICFILES_DIRS to the settings.py file and set the static file directory path with templates.
1 STATIC_URL = '/static/'
2 STATICFILES_DIRS = [
3     os.path.join(BASE_DIR, 'static')
4 ]
  • Quote
    • Create templates / templates/studentlogin.html
 1 {% load static %}
 2 <!DOCTYPE html>
 3 <html lang="zh-CN">
 4   <head>
 5     <meta charset="utf-8">
 6     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7     <meta name="viewport" content="width=device-width, initial-scale=1">
 8     <meta name="description" content="">
 9     <meta name="author" content="">
10     <title>Signin Template for Bootstrap</title>
11     <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
12     <link href="{% static 'student/css/signin.css' %}" rel="stylesheet">
13   </head>
14 </html>
15 <!-- Only part of the code -->
    • Create / static/student/css/signin.css
 1 body {
 2   padding-top: 40px;
 3   padding-bottom: 40px;
 4   background-color: #eee;
 5 }
 6 
 7 .form-signin {
 8   max-width: 330px;
 9   padding: 15px;
10   margin: 0 auto;
11 }
12 .form-signin .form-signin-heading,
13 .form-signin .checkbox {
14   margin-bottom: 10px;
15 }
16 .form-signin .checkbox {
17   font-weight: normal;
18 }
19 .form-signin .form-control {
20   position: relative;
21   height: auto;
22   -webkit-box-sizing: border-box;
23      -moz-box-sizing: border-box;
24           box-sizing: border-box;
25   padding: 10px;
26   font-size: 16px;
27 }
28 .form-signin .form-control:focus {
29   z-index: 2;
30 }
31 .form-signin input[type="email"] {
32   margin-bottom: -1px;
33   border-bottom-right-radius: 0;
34   border-bottom-left-radius: 0;
35 }
36 .form-signin input[type="password"] {
37   margin-bottom: 10px;
38   border-top-left-radius: 0;
39   border-top-right-radius: 0;
40 }
    • Introduction of student/views.py
1 def login(request):
2     return render(request, 'student/login.html')
    • Introduction of student/urls.py
1 urlpatterns = [
2     path('login/', views.login),
3 ]
  • Design sketch

Posted by macpaul on Fri, 10 May 2019 01:16:41 -0700