Django入门指南09-templates模板引擎

690次阅读
没有评论

Django 模板引擎设置

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

myproject/

 |– myproject/

 |    |– boards/

 |    |– myproject/

 |    |– templates/   <– 这里

 |    +– manage.py

 +– venv/

在templates文件夹中,创建一个名为home.html的HTML文件:

templates/home.html

<!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>

在上面的例子中,我们混入了原始HTML和一些特殊标签 {% for … in … %} 和 {{ variable }} 。它们是Django模板语言的一部分。上面的例子展示了如何使用 for遍历列表对象。{{ board.name }}会在 HTML 模板中会被渲染成版块的名称,最后生成动态HTML文档。

在我们可以使用这个HTML页面之前,我们必须告诉Django在哪里可以找到我们应用程序的模板。

打开myproject目录下面的settings.py文件,搜索TEMPLATES变量,并设置DIRS 的值为 os.path.join(BASE_DIR, 'templates'):

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',
            ],
        },
    },
]

本质上,刚添加的这一行所做的事情就是找到项目的完整路径并在后面附加“/templates”

我们可以使用Python shell进行调试:

python manage.py shell
from django.conf import settings
settings.BASE_DIR
'/Users/vitorfs/Development/myproject'
import os
os.path.join(settings.BASE_DIR, 'templates')
'/Users/vitorfs/Development/myproject/templates'

看到了吗?它只是指向我们在前面步骤中创建的templates文件夹。

现在我们可以更新home视图:

boards/views.py
from django.shortcuts import render
from .models import Board
def home(request):
    boards = Board.objects.all()
    return render(request, 'home.html', {'boards': boards})

生成的HTML:

Django入门指南09-templates模板引擎

我们可以table表示替换,改进HTML模板:

templates/home.html
<!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>

Django入门指南09-templates模板引擎

下一节:Django入门指南10-主页的请求测试

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-11-09发表,共计2591字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)