Django教程-Django模板
Django 提供了一种使用其模板系统生成动态 HTML 页面的便捷方法。
模板由所需 HTML 输出的静态部分以及描述如何插入动态内容的一些特殊语法组成。
为什么选择 Django 模板?
在HTML文件中,我们不能编写Python代码,因为代码只能由Python解释器解释,而不是浏览器。我们知道HTML是一种静态标记语言,而Python是一种动态编程语言。
Django模板引擎用于将设计与Python代码分离,并允许我们构建动态网页。
Django 模板配置
要配置模板系统,我们必须在settings.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',],},},]
👉点击领取Python面试题手册
Django 模板简单示例
首先,在项目应用程序中创建一个目录模板,如下所示。
之后在创建的文件夹中创建一个模板index.html 。
我们的模板index.html包含以下代码。
// 索引.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Index</title></head><body><h2>Welcome to Django!!!</h2></body></html>
加载模板
要加载模板,请像下面一样调用 get_template() 方法并传递模板名称。
//视图.py
from django.shortcuts import render#importing loading from django templatefrom django.template import loader# Create your views here.from django.http import HttpResponsedef index(request):template = loader.get_template('index.html') # getting our templatereturn HttpResponse(template.render()) # rendering the template in HttpResponse
//urls.py
path('index/', views.index),INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','myapp']
运行服务器
执行以下命令,并在浏览器中输入localhost:8000/index访问模板。
$ python3 manage.py runserverDjango 模板语言
Django 模板使用自己的语法来处理变量、标签、表达式等。模板是使用上下文来呈现的,该上下文用于在网页上获取值。请参阅示例。
变量
与上下文关联的变量可以通过 {{}}(双花括号)访问。例如,变量名称值为 rahul。然后以下语句将用其值替换名称。
My name is {{name}}.My name is rahul
Django 变量示例
//视图.py
from django.shortcuts import render#importing loading from django templatefrom django.template import loader# Create your views here.from django.http import HttpResponsedef index(request):template = loader.get_template('index.html') #获取我们的模板name = {'student':'rahul'}return HttpResponse(template.render(name)) #在 HttpResponse中渲染模板
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Index</title></head><body><h2>Welcome to Django!!!</h2><h3>My Name is: {{ student }}</h3></body></html>
标签
在模板中,标签在渲染过程中提供任意逻辑。例如,标签可以输出内容、用作控制结构(例如“if”语句或“for”循环)、从数据库中获取内容等。
标签由 {% %} 大括号括起来。例如。
{% csrf_token %}{% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}