Django入门与实践-第7章:模板引擎设置

在manage.py所在的目录创建一个名为 templates的新文件夹:

1
2
3
4
5
6
7
myproject/
|-- myproject/
| |-- boards/
| |-- myproject/
| |-- templates/ <-- 这里
| +-- manage.py
+-- venv/

templates/home.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Boards</title>
</head>
<body>
<h1>Boards</h1>

{% for board in boards %}
{{ board.name }} <br>
{% endfor %}

</body>
</html>

告诉Django在哪里可以找到我们应用程序的模板

settings.py文件,搜索TEMPLATES变量,并设置DIRS 的值为 os.path.join(BASE_DIR, 'templates')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(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',
],
},
},
]

更新home视图:

boards/views.py

1
2
3
4
5
6
from django.shortcuts import render
from .models import Board

def home(request):
boards = Board.objects.all()
return render(request, 'home.html', {'boards': boards})

生成的HTML:

7-1

templates/home.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Boards</title>
</head>
<body>
<h1>Boards</h1>

<table border="1">
<thead>
<tr>
<th>Board</th>
<th>Posts</th>
<th>Topics</th>
<th>Last Post</th>
</tr>
</thead>
<tbody>
{% for board in boards %}
<tr>
<td>
{{ board.name }}<br>
<small style="color: #888">{{ board.description }}</small>
</td>
<td>0</td>
<td>0</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

7-2

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2021 朝着牛逼的道路一路狂奔 All Rights Reserved.

访客数 : | 访问量 :