Python Django 母版和继承解析

yipeiwu_com6年前Python基础

可以把多个页面相同的部分提取出来,放在一个母板里,这些页面只需要继承这个母板就好了

通常会在母板中定义页面专用的 CSS 块和 JS 块,方便子页面替换

定义块:

{% block 名字 %}
{% endblock %}

views.py 中添加函数:

from django.shortcuts import render, redirect, HttpResponse
from app01 import models
import datetime
def muban_test(request):
  return render(request, "muban_test.html")

urls.py 中添加对应关系:

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
  # 母板
  url(r'^muban_test/', views.muban_test),
]

muban.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<hr>
{# 定义母板 #}
{% block page-main %}
{% endblock %}
<hr>
</body>
</html>

muban_test.html:

{# 首先继承母板 #}
{% extends 'muban.html' %}
{# 这里的名字 page-main 和继承的母板的名字要相符 #}
{% block page-main %}
  <h1>hello world</h1>
{% endblock %}<br data-filtered="filtered"><br data-filtered="filtered"><h1>Test</h1>

运行结果:

可以看到,muban_test.html 中没有写 hr,但是显示了从 muban.html 继承过来的 hr

muban_test.html 中写的 test 也没有显示出来,因为它是把块中的内容贴到母板中块的部分

views.py 函数中 return 的是 muban_test.html,而不是 muban.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现测试磁盘性能的方法

本文实例讲述了Python实现测试磁盘性能的方法。分享给大家供大家参考。具体如下: 该代码做了如下工作: create 300000 files (512B to 1536B) with...

python实现杨辉三角思路

程序输出需要实现如下效果: [1] [1,1] [1,2,1] [1,3,3,1] ...... 方法:迭代,生成器 def triangles() L = [1] while...

Python 3中的yield from语法详解

前言 最近在捣鼓Autobahn,它有给出个例子是基于asyncio 的,想着说放到pypy3上跑跑看竟然就……失败了。 pip install asyncio直接报invalid sy...

python实现机器人卡牌

python实现机器人卡牌

介绍 这个例子主要利用turtle库实现根据输入动态展示不同机器人的图像和属性信息。 代码部分非原创只是做了些许修改和整理使得更易阅读。 图片和文件资源请访问git仓库获取:链接地址 涉...

Python判断一个list中是否包含另一个list全部元素的方法分析

本文实例讲述了Python判断一个list中是否包含另一个list全部元素的方法。分享给大家供大家参考,具体如下: 你可以用for in循环+in来判断 #!/usr/bin/env...