码迷,mamicode.com
首页 > 其他好文 > 详细

django模板中的extends和include使用方法

时间:2019-08-07 22:33:04      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:head   utf-8   oct   作用   ret   特性   相同   通过   https   

一、extends使用方法

首先extends也就是继承,子类继承父类的一些特性。在django模板中通过继承可以减少重复代码。

首先我们建立一个app,名字叫做hello。别忘了在settings.py中的INSTALLED_APPS注册这个app。不注册会出现hello目录下的templates中的模板无法调用。

1.在根目录下的templates创建base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

这里的block就是继承后要被替换的内容,其他的则与该模板相同

2.在hello这个app中继承这个模板

在hello目录下新建templates目录,再在此目录下新建hello目录。hello目录中新建hello.html。目录结构就像这样,理解一下django模板引用路径的规则

技术图片

hello.html内容如下

{% extends ‘base.html‘ %}
{% block title %}{{ title }}{% endblock %}
{% block content %}{{ content }}{% endblock %}

首行代码就是先继承base.html,也就是有了除了block的剩下内容。后面两个则是在为block填空,填入的内容是要传入的参数。这里分别是title和content。这里可以看出模板语句是单个大括号加百分号,而模板变量是双大括号,没有百分号。

3.添加路由和方法

路由文件urls.py内容如下

from django.contrib import admin
from django.urls import path
from hello import views

urlpatterns = [
    path(hello/<str:title>/<str:content>/,views.hello),
    path(admin/, admin.site.urls),
]

注意在路径中获取参数的方法,str还可以换为int。我觉得这种传参的方法比较简单容易理解,看了还有正则表达式的传参方法不是很直观,以后有机会再仔细学。

hello app中的views.py

from django.shortcuts import render

# Create your views here.
def hello(request,title,content):
    context={title:title,content:content}
    return render(request,hello/hello.html,context)

这里函数的形参名就是在路由中获取的参数名。通过传递参数会render给hello.html这个模板,而hello.html这个模板又会继承base.html这个父模板。

实现效果如下

技术图片

 

4.总结extends

通过extends可以减少代码重复。可以再增加header、footer等来包含共同的头部和底部内容。其实我是先找到的include,但是include要么放在head中,可以减少重复引入css或js,要么放在body中当一个共同的导航条,或者底部内容。然而如果要在多处都include就不如直接用extends了。

二、include使用方法

这里我们在hello下新建hello2.html和hello3.html。

hello2.html内容如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello2</title>
</head>
<body>
{% include hello/hello3.html %}
</body>
</html>

hello3.html内容如下

<p>
    this is a p in hello3.html
</p>

可以看出,hello2.html包含了hello3.html中的内容。这样也达到了减少重复代码的作用。再添加views中hello2方法

def hello2(request):
    return render(request,hello/hello2.html)

以及urls中添加hello2

from django.contrib import admin
from django.urls import path
from hello import views

urlpatterns = [
    path(hello2/,views.hello2),
    path(hello/<str:title>/<str:content>/,views.hello),
    path(admin/, admin.site.urls),
]

实现效果如下

技术图片

最近写了一个校内二手书交易平台的demo,很粗糙,就是个练练手的实战吧算是,欢迎来看看roadwide/campus_bookmarket

 

django模板中的extends和include使用方法

标签:head   utf-8   oct   作用   ret   特性   相同   通过   https   

原文地址:https://www.cnblogs.com/roadwide/p/11318048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!