Django入门与实践-第12章:复用模板

    在这一节我们将重写 HTML 模板,创建一个 master page(母版页),其他模板添加它所独特的部分。

    templates 文件夹中创建一个名为 base.html 的文件: {% raw %}

    templates/base.html

    这是我们的母版页。每个我们创建的模板都 extend(继承) 这个特殊的模板。现在我们介绍 标签。它用于在模板中保留一个空间,一个”子”模板(继承这个母版页的模板)可以在这个空间中插入代码和 HTML。

    {% block title %} 中我们还设置了一个默认值 “Django Boards.”。如果我们在子模板中未设置 {% block title %} 的值它就会被使用。

    现在让我们重写我们的两个模板: home.htmltopics.html

    templates/home.html

    1. {% extends 'base.html' %}
    2. {% block breadcrumb %}
    3. <li class="breadcrumb-item active">Boards</li>
    4. {% endblock %}
    5. {% block content %}
    6. <table class="table">
    7. <thead class="thead-inverse">
    8. <tr>
    9. <th>Board</th>
    10. <th>Posts</th>
    11. <th>Topics</th>
    12. <th>Last Post</th>
    13. </tr>
    14. </thead>
    15. <tbody>
    16. {% for board in boards %}
    17. <tr>
    18. <a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a>
    19. <small class="text-muted d-block">{{ board.description }}</small>
    20. </td>
    21. <td class="align-middle">0</td>
    22. <td class="align-middle">0</td>
    23. <td></td>
    24. </tr>
    25. {% endfor %}
    26. </tbody>
    27. </table>
    28. {% endblock %}

    templates/topics.html

    topics.html 中,我们改变了 {% block title %} 的默认值。注意我们可以通过调用 {{ block.super }} 来重用 block 的默认值。这里我们使用的网页标题是 base.html 中定义的 “Django Boards”。所以对于 “Python” 的 board 页面,这个标题是 “Python - Django Boards”,对于 “Random” board 标题会是 “Random - Django Boards”。

    现在我们运行测试,然后会看到我们没有破坏任何东西:

    1. python manage.py test

    棒极了!一切看起来都很成功。

    现在我们有了 bast.html 模板,我们可以很轻松地在顶部添加一个菜单块:

    templates/base.html

    1. {% load static %}<!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <title>{% block title %}Django Boards{% endblock %}</title>
    6. <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    7. <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    8. <div class="container">
    9. <a class="navbar-brand" href="{% url 'home' %}">Django Boards</a>
    10. </div>
    11. </nav>
    12. <div class="container">
    13. <ol class="breadcrumb my-4">
    14. {% block breadcrumb %}
    15. {% endblock %}
    16. </ol>
    17. {% block content %}
    18. {% endblock %}
    19. </div>
    20. </body>
    21. </html>

    我使用的 HTML 是 的一部分。

    我喜欢的一个比较好的改动是改变页面的 “logo”(.navbar-brand)。

    前往 fonts.google.com,输入 “Django Boards” 或者任何你项目给定的名字然后点击 apply to all fonts(应用于所有字体)。浏览一下,找到一个你喜欢的字体。

    3-13.png

    bast.html 模板中添加这个字体:

    现在在 static/css 文件夹中创建一个新的 CSS 文件命名为 app.css

    static/css/app.css

    1. .navbar-brand {
    2. font-family: 'Peralta', cursive;

    {% endraw %}