个性化阅读
专注于IT技术分析

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', ], }, }, ]

在这里, 我们提到我们的模板目录名称是template。默认情况下, DjangoTemplates在每个INSTALLED_APPS中寻找一个模板子目录。

Django模板简单示例

首先, 如下所述, 在项目应用程序内创建目录模板。

django模板

之后, 在创建的文件夹中创建一个模板index.html。

django模板1

我们的模板index.html包含以下代码。

// index.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()方法并传递模板名称。

//views.py

from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
   template = loader.get_template('index.html') # getting our template
   return HttpResponse(template.render())       # rendering the template in HttpResponse

设置URL以从浏览器访问模板。

//urls.py

path('index/', views.index), 

在INSTALLED_APPS中注册应用

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 runserver
django模板2

Django模板语言

Django模板使用其自己的语法来处理变量, 标签, 表达式等。模板通过上下文呈现, 该上下文用于在网页上获取价值。请参阅示例。

变数

{{}}(双花括号)可以访问与上下文关联的变量。例如, 变量名称值为rahul。然后, 以下语句将name替换为其值。

My name is {{name}}. 
My name is rahul

Django变量示例

//views.py

from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
    template = loader.get_template('index.html') # getting our template
    name = {
        'student':'rahul'
    }
    return HttpResponse(template.render(name))       # rendering the template in HttpResponse

//index.html

<!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>

输出:

django模板3

标签

在模板中, 标签在渲染过程中提供了任意逻辑。例如, 标签可以输出内容, 用作例如控件的控制结构。 “ if”语句或“ for”循环, 从数据库中获取内容等。

标签用{%%}大括号括起来。例如。

{% csrf_token %}

{% if user.is_authenticated %}
	Hello, {{ user.username }}.
{% endif %}
赞(0)
未经允许不得转载:srcmini » Django模板

评论 抢沙发

评论前必须登录!