首页 > 编程 > Python > 正文

Django模板Templates使用方法详解

2019-11-25 12:18:04
字体:
来源:转载
供稿:网友

一、django的模板:

在settings.py的文件中可以看到并设置这个模板。

1.直接映射:

通过建立的文件夹(templates)和文件(html)来映射。

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Title</title></head><body>  <h1>Hello World!</h1></body></html>
from django.shortcuts import renderfrom django.http import HttpResponse# Create your views here.def index(request):  return render(request, 'index.html', {"Jhy": "I love your!"})

2.通过DTL(django templates language)的实现方式:

在创建一个新的templates的文件夹,在新建一个html的文件。

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Title</title></head><body>   <h1>{{Jhy}}</h1></body></html>

在<h1>的标签中添加了关于render(渲染)的第三个参数的键值。

这个参数是一个dict的数据类型

 def index(request):   return render(request, 'index.html', {"Jhy": "I love your!"})

其中render的第一个参数就是index的参数,第二个为templates的下的html文件,第三个就是通过dict的数据类型存储templates将要映射的东西。

3.注意:

当有两个应用的templates中相同名字的html文件时,django会根据添加的顺序来进行映射,解决方法:

建立一个和App同名的文件夹,将html文件放入该文件下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表