Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Django 添加主模板


extends 标签

在前面的页面中,我们创建了两个模板,一个用于列出所有成员,另一个用于显示成员的详细信息。

这两个模板都包含一些相同的 HTML 代码。

Django 提供了一种方法来创建一个“父模板”,你可以将其包含在所有页面中,以处理所有页面中相同的部分。

首先创建一个名为 master.html 的模板,包含所有必要的 HTML 元素。

主模板

my_tennis_club/members/templates/master.html:

<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}{% endblock %}</title>
</head>
<body>

{% block content %}
{% endblock %}

</body>
</html>

你是否看到了 <title> 元素和 <body> 元素内部的 Django 块标签?

它们是占位符,告诉 Django 用来自其他来源的内容替换此块。


修改模板

现在这两个模板(all_members.htmldetails.html)可以使用这个 master.html 模板。

这是通过使用 {% extends %} 标签包含主模板,并插入 title 块和 content 块来实现的。

成员

my_tennis_club/members/templates/all_members.html:

{% extends "master.html" %}

{% block title %}
  My Tennis Club - List of all members
{% endblock %}


{% block content %}
  <h1>Members</h1>
  
  <ul>
    {% for x in mymembers %}
      <li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li>
    {% endfor %}
  </ul>
{% endblock %}
运行示例 »

详情

my_tennis_club/members/templates/details.html:

{% extends "master.html" %}

{% block title %}
  Details about {{ mymember.firstname }} {{ mymember.lastname }}
{% endblock %}


{% block content %}
  <h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1>
  
  <p>Phone {{ mymember.phone }}</p>
  <p>Member since: {{ mymember.joined_date }}</p>
  
  <p>Back to <a href="/members">Members</a></p>
  
{% endblock %}
运行示例 »

如果你在自己的电脑上完成了所有步骤,你可以在自己的浏览器中看到结果:127.0.0.1:8000/members/

如果服务器已关闭,你需要使用 runserver 命令重新启动它。

py manage.py runserver

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.