栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django框架之模板层template的一些介绍和使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django框架之模板层template的一些介绍和使用

文章目录
  • Django模板层
  • Django模板层配置
  • Django模板层变量调用、代码嵌入与过滤器
    • 变量调用
    • python代码嵌入
    • 过滤器
  • Django模板层继承

Django模板层

Django的模板层负责呈现内容到浏览器,简单来说就是用来放HTML等静态网页的东西的,便于前端界面的管理以及django自身的调用。

Django模板层配置

首先在manage.py同目录下创建templates文件夹,用于放HTML等文件。

然后我们需要告诉django模板放在哪里,因此还需要配置文件setting.py配置对应模板层的路径。

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文件夹下创建一个test_html.html
内容如下:




    
    
    
    Document


    模板层!!!hello world !!



随便放点东西就可以。

然后配置对应的路由和视图
配置视图
views.py:

from django.shortcuts import render
from django.http import HttpResponse

def test_html(request):
    return render(request, "test_html.html")

由于使用模板层,因此对应调用的代码也会简便许多。

配置路由
urls.py:

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path("test_html", views.test_html),
]

然后运行服务器即可。
打开浏览器进入http://127.0.0.1:8000//test_html
看到以下内容说明模板层配置成功!

Django模板层变量调用、代码嵌入与过滤器

django的模板层网页变量数据的传输很方便,直接{{变量名}}即可传输,和jsp中java变量传输到网页之中差不太多,当然django模板层同样也能够嵌入python代码。

变量调用

django中能够传递的数据类型如下:
str、int、list、tuple、dict、func、obj

传递的方法列举:
{{变量名}}
{{变量名.index}}
{{变量名.key}}
{{变量名.方法}}
{{函数名}}

接下来举个例子应该就懂怎么操作了。

首先配置视图函数view.py:

from django.shortcuts import render
from django.http import HttpResponse

def hello():
    return "hello world"

class dog():
    def say(self):
        return "hellllllllll"

def test_html(request):
    dic = {}
    dic["int"] = 88
    dic["str"] = "good"
    dic["list"] = ["A", "B", "C"]
    dic["dicts"] = {"A":555, "B":666}
    dic["func"] = hello
    dic["obj"] = dog()
    return render(request, "test_html.html", dic)

数据传输都只能够通过字典的形式传输过去,我们这里传输了一个int、一个str、一个list、一个字典、一个函数以及一个对象过去。

然后配置模板层的网页内容,templates文件夹下的test_html.html如下:




    
    
    
    Document


    模板层!!!hello world !!{{username}}
    
int {{int}}
str {{str}}
list_one {{list.1}}
dicts {{dicts.A}}
func {{func}}
obj {{obj.say}}

看代码应该就知道各种类型该怎么调用了。

配置路由urls.py:

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path("test_html", views.test_html),
]

然后运行服务器,访问http://127.0.0.1:8000//test_html


能够看到变量都能够传输过来了。其中比较需要注意的就是列表元素的索引是 变量名.index(索引号)来索引。

python代码嵌入

python代码嵌入的话,语法应该差不多,只需要在<%%>中输入python代码即可调用。
我们接着刚才的配置,只需要将test_html.html中的内容加上python代码的调用即可看到效果。
test_html.html:




    
    
    
    Document


    模板层!!!hello world !!{{username}}
    
int {{int}}
str {{str}}
list_one {{list.1}}
dicts {{dicts.A}}
func {{func}}
obj {{obj.say}}
{%if dicts.A > 100 %} hello world {%else %} good mornings world {%endif %} {% for i in list%} {{i}} {%empty%} 空的 {%endfor %}

运行服务器可得到:

最下面一行就是嵌入的python代码发挥的作用。

过滤器

模板过滤器,能通过过滤器来改变变量的输出显示
语法:{{变量|过滤器}}


举个例子就懂了。
views.py:

from django.shortcuts import render
from django.http import HttpResponse

def hello():
    return "hello world"

class dog():
    def say(self):
        return "hellllllllll"

def test_html(request):
    dic = {}
    dic["int"] = 88
    dic["str"] = "good"
    dic["list"] = ["A", "B", "C"]
    dic["dicts"] = {"A":555, "B":666}
    dic["func"] = hello
    dic["obj"] = dog()
    dic["script"] = ""
    return render(request, "test_html.html", dic)

test_html.html:




    
    
    
    Document


    模板层!!!hello world !!{{username}}
    
int {{int | add:"50"}}
str {{str | upper}}
list_one {{list.1}}
dicts {{dicts.A}}
func {{func}}
obj {{obj.say}}
script {{script | safe}}

路由没变,还是上一个例子的那个。
运行服务器,应该会有一个弹窗,然后int会加上50,str会变成大写。

Django模板层继承

平时上网的时候,我们可以发现很多网站里的网页都是有类似之处的,例如同一个网站里,最上面的导航栏以及最下面的版权块等等都是相同的,只是网页中间的核心内容变化了,为了提高代码的复用性,提高开发效率,django能够实现模板层的集成和重写,和面向对象的操作差不多。

下面举个例子就能直观的体会了。

首先配置路由,这里我们需要配置两个路由,分别进入父网页和子网页
urls.py:

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path("father", views.father),
    path("child", views.child)
]

然后我们配置对应的视图函数:
views.py:

from django.shortcuts import render
from django.http import HttpResponse

def father(request):
    dic = {}
    dic["a"] = 10
    return render(request, "father.html", dic)

def child(request):
    return render(request, "child.html")

最后我们需要配置对应的HTML,在templates文件夹下分别配置父网页和子网页的HTML。

django继承可修改的部分是以下格式:

{%block 块名%}
##########
{%endblock%}

这个块名中的东西如果被重写则会覆盖,剩余的东西则会被原封不动的继承下来。
那么father.html如下:




    
    
    
    Document


    2022----------------------------------
    
{%block info %} 这是主页 {%endblock %}

child.html如下:

{% extends "father.html"%}
{%block info%}
你好,欢迎光临,谢谢惠顾
{%endblock%}

其中{% extends “father.html”%}表示继承father,html的内容,然后又重写了info块中的内容,因此会覆盖原内容,因此最后启动服务器后的结果如下:


可以发现只是修改了block info中的内容。
值得注意的是,模板继承时,模板传入的变量是无法继承的

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/989457.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号