django模板

In this tutorial, we’ll learn what is Django Templates. We’ll later implement them in a simple Python Web Application.

在本教程中,我们将学习什么是Django模板。 稍后,我们将在一个简单的Python Web应用程序中实现它们。

快速Django设定 (Quick Django Setup)

Let’s follow the steps from Django tutorial to set up our Virtual Environment, Django Project and Django App from the command line terminal quickly.

让我们按照Django教程中的步骤操作,以从命令行终端快速设置虚拟环境,Django Project和Django App。

Goto the directory where you want to create the new Project and run the following commands sequentially.

转到要在其中创建新项目的目录,然后依次运行以下命令。

$mkdir DjangoWorld
$cd DjangoWorld
$virtualenv -p /usr/local/bin/python3 env
$source env/bin/activate
$pip3 install django
$django-admin startproject TemplateProject .
$django-admin startapp TemplateApp
$python3 manage.py migrate
$python3 manage.py runserver

Add TemplateApp to the settings.py file present in the TemplateProject. I am using Atom IDE for this tutorial.

添加TemplateApp到settings.py存在于文件TemplateProject 。 我在本教程中使用Atom IDE。

Create a new folder template inside the Django App directory – TemplateApp. Inside the template folder we’ll create our html files.

在Django App目录– TemplateApp创建一个新的文件夹template 。 在template文件夹内,我们将创建html文件。

Our final project structure of the web application looks like this:

Web应用程序的最终项目结构如下所示:

We need to create a urls.py file in the TemplateApp too. There we’ll define the URL patterns for the app.

我们也需要在TemplateApp中创建一个urls.py文件。 在那里,我们将为应用程序定义URL模式。

We need to include that URL file in our TemplateProject urls.py file present in TemplateProject folder.

我们需要将该URL文件包含在TemplateProject文件夹中存在的TemplateProject urls.py文件中。

urlpatterns = [re_path('admin/', admin.site.urls),re_path(r'^', include('TemplateApp.urls')) # tell django to read urls.py in TEMPLATESapp
]
]

Django模板 (Django Templates)

In our previous tutorial, we’d set the HTML code in our views.py file of the Django App.

在之前的教程中,我们将在Django应用程序的views.py文件中设置HTML代码。

In the views.py file, we can write the following design code for the Django website;

在views.py文件中,我们可以为Django网站编写以下设计代码;

def current_datetime(request):today = datetime.datetime.now()html = "<html><body>It is today %s.</body></html>" % todayreturn HttpResponse(html)

Hardcoding HTML code in the Python code isn’t the best way to build a website.

用Python代码对HTML代码进行硬编码并不是构建网站的最佳方法。

HTML codes can go to thousands of lines. We don’t wish to write those 1000 lines in our Python code since they aren’t related to Python in any way. It’ll become very hard to manage such projects.

HTML代码可以行数千行。 我们不希望在Python代码中写那1000行,因为它们与Python毫无关系。 管理此类项目将变得非常困难。

This is where Django Templates will come to our rescue.

这就是Django模板将为我们提供帮助的地方。

Django Templates are basic HTML code which includes Django Template Language. This special syntax is used to pass values from the Django Views python classes to the HTML codes.

Django模板是基本HTML代码,其中包括Django模板语言 。 这种特殊的语法用于将值从Django Views python类传递到HTML代码。

How is the data from the views.py passed to the Templates?

如何将views.py中的数据传递给模板?

Using Render functions. Render functions are used in place of HttpResponse to display data in Django Templates.

使用渲染功能。 渲染函数用于代替HttpResponse在Django模板中显示数据。

A render function consists of three things:

渲染功能由三部分组成:

  • Request instance请求实例
  • Path to html filehtml文件的路径
  • Context语境

The context in Django Templates is like a Dictionary. It consists of key-value pairs that are passed from the Django View to the Django Template.

Django模板中的上下文就像字典。 它由从Django视图传递到Django模板的键/值对组成。

Django模板语言 (Django Template Language)

Variables are defined as : {{ variable }}. The variable is passed in the Context key.

变量定义为: {{ variable }} 。 该变量在Context键中传递。

<html><body>Hello {{variable}}</p></body></html>

This template is called from the Django view:

从Django视图调用此模板:

def hello(request):variable = 'Anupam'return render(request, "hello.html", {'variable' : variable})

Django模板过滤器 (Django Template Filters)

We can modify the variable in the Django Templates using the filter. Filter is set after a | character.

我们可以使用过滤器在Django模板中修改变量。 在|后设置过滤器 字符。

{{variable|upper}} – Displays the value of the variable in uppercase.

{{variable|upper}} –以大写形式显示变量的值。

{{variable|slice:":-5"}} removes the last 5 characters from the variable.

{{variable|slice:":-5"}}从变量中删除最后5个字符。

Django模板标签 (Django Template Tags)

Tags in Django Templates are used for expressions. if elif, for loops are typically used.
A Tag is defined like:
{% tag %} – In place of tag you can set your expression.

Django模板中的标签用于表达式。 如果为elif,则通常使用for循环。
标签的定义如下:
{% tag %} –可以代替标签来设置表达式。

It is required to start and close the tag as shown below:

需要启动和关闭标签,如下所示:

<ul>
{% for x in python_list %}<li>{{ x.name }}</li>
{% endfor %}
</ul>

if elif – else

如果是elif –否则

% if python_list|length > 10 %}<h2>Number of rows: {{ python_list|length }}</h2>{% elif story_list|length == 1 %}<h2>One row</h2>{% else %}<p>No rows<p>{% endif %}

创建Django Web应用程序 (Creating Django Web Application)

First, goto settings.py in the TemplateProject and add the path to the template directory in the TEMPLATE list on the DIR key.

首先,转到TemplateProject中的settings.py并将路径添加到DIR键上TEMPLATE列表中的template目录。

django.contrib.admin templates are written in DTL. There is a popular alternative for DTL, namely django.contrib.admin模板是用DTL编写的。 DTL有一个流行的替代方法,即jinja2 but we’ll discuss that some other time.jinja2但我们将在以后再讨论。

We’ll be crHTMLng three html pages in our web application – home, about and more.html.

我们将在Web应用程序中crHTMLng三个html页面– home,about和more.html。

First set the url patterns in the urls.py file present in the TemplateApp folder as shown below:

首先,在TemplateApp文件夹中的urls.py文件中设置url模式,如下所示:

from django.conf.urls import urlfrom . import viewsurlpatterns = [url(r'^$', views.home, name='home'),url(r'^about/$', views.about, name='about'),url(r'^more/$', views.MorePageView.as_view(), name='more'),
]

Here views refers to the views.py file.

这里的views是指views.py文件。

MorePageView is a Python class in which we define the Template as a View instead of rendering.

MorePageView是Python类,其中我们将模板定义为视图而不是呈现。

You can use either of Rendering function or TemplateViews.

您可以使用“渲染”功能或“模板视图”。

The code for the views.py file is given below.

下面给出了views.py文件的代码。

from django.shortcuts import render
from django.http import HttpResponsefrom django.views.generic import TemplateView# # Create your views here.
def home(request):return render(request,'home.html',{})data = [
{'name': 'JournalDev.com','link': 'https://www.journaldev.com'},
{'name': 'Android ListView','link': 'https://www.journaldev.com/9247/android-listview-example-tutorial'},
{'name': 'Android RecyclerView','link': 'https://www.journaldev.com/10024/android-recyclerview-android-cardview-example-tutorial'},
{'name': 'Android P Features','link': 'https://www.journaldev.com/21178/android-p-features'},
{'name': 'More...','link': 'more.html'},
]def about(request):context = {'data_list' : data}return render(request,'about.html',context)class MorePageView(TemplateView):template_name = "more.html"

Make sure you stick to a consistent indentation since Python is indentation sensitive.

由于Python对缩进敏感,因此请确保坚持一致的缩进。

We’re passing no Context to the home.html Django Template.

我们没有将上下文传递给home.html Django模板。

The about function renders the about.html template. In it, we pass a Python Dictionary of urls of some Android Tutorial along with an internal link to the more.html project.

about函数呈现about.html模板。 在其中,我们传递了一些Android教程的URL的Python字典以及指向more.html项目的内部链接。

In the Python class above, we’re directly invoking the Django Template through it’s class name. We’re not passing any Context.

在上面的Python类中,我们通过其类名直接调用Django模板。 我们没有传递任何上下文。

If you want to pass Context using this method of TemplateView, do the following:

如果要使用TemplateView的此方法传递Context,请执行以下操作:

class MorePageView(TemplateView):def get(self, request, **kwargs):context = {'data_list' : data}return render(request, 'more.html', context)

The get method returns the list of all templates.

get方法返回所有模板的列表。

Let’s look at each of the Django Template Html files below:

让我们看一下下面的每个Django模板HTML文件:

home.html

home.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Home</title>
</head>
<body><h1>Our First Template</h1><p>We'll be covering the following features:<ol><li>Rendering Templates from Views</li><li>Passing data to Templates from Views</li><li>Django Template Syntax</li></ol></p>
<a href="{% url 'about' %}">About</a></body>
</html>

At the bottom, we provide a link to the about.html page using Django Template tags. {% url 'name_defined_in_urls' %}.

在底部,我们使用Django模板标签提供了指向about.html页面的链接。 {% url 'name_defined_in_urls' %}

We’ve used Automatic URL reverse lookup since the names are already defined in the urls.py file.
This makes it short and concise.

由于已经在urls.py文件中定义了名称,因此我们使用了自动URL反向查找。
这使其简洁明了。

about.html

about.html

<html lang="en">
<head><meta charset="UTF-8"><title>About Us</title>
</head>
<body><p>This webpage consists of some of the JournalDev tutorial external links:<ol><li>Checkout the logic to differentiate external and internal links.</li><li>Django Templates has for loops for you.</li></ol></p>{% for data in data_list %}{% if '.html' in data.link %}<p><a href="{% url data.link|slice:":-5" %}">{{ data.name|upper }} </a></p>{% else %}<p><a href="{{ data.link }}" target="_self">{{ data.name }} </a></p>{% endif %}{% endfor %}<a href="{% url 'home' %}">Go Home</a></body>
</html>

In the above code, we check if the URL is external or internal.

在上面的代码中,我们检查URL是外部还是内部。

If it is an external url, we set target = _self in the a href.

如果是外部网址,则在a href设置target = _self

Otherwise using the slice operator we remove the extension from the Django Variable and do a url reverse lookup.

否则,使用slice运算符,我们从Django变量中删除扩展名,并执行url反向查找。

The code for the more.html file is given below:

下面给出了more.html文件的代码:

<html lang="en">
<head><meta charset="UTF-8"><title>More</title>
</head>
<body>That's all for now.See you later. <br><a href="{% url 'about' %}">About</a> <a href="{% url 'home' %}">Home</a>
</body>
</html>

On your terminal run the command python3 manage.py runserver:

在终端上运行命令python3 manage.py runserver

The output in your web browser should be like:

您的网络浏览器中的输出应类似于:

So in this tutorial, we made a Django Web Application in which we could pass a Python List of external and internal url links to the Django Templates and play around with them.

因此,在本教程中,我们制作了一个Django Web应用程序,可以在其中将外部和内部url链接的Python列表传递给Django模板,并对其进行处理。

You can download the source code from the link below. Just go inside the root directory and set the virtual environment and activate it. Your web application would be ready.

您可以从下面的链接下载源代码。 只需进入根目录并设置虚拟环境并激活它即可。 您的Web应用程序将准备就绪。

Django Templates Project.Django模板项目 。

翻译自: https://www.journaldev.com/21210/django-templates

django模板

django模板_Django模板相关推荐

  1. Django 视图和模板1.4

    视图 在django中,视图对WEB请求进行回应 视图接收reqeust对象作为第一个参数,包含了请求的信息 视图就是一个Python函数,被定义在views.py中 #coding:utf-8 fr ...

  2. Django模板之django自带模板

    模板 知识点 自带模板 基本使用 流程控制 过滤器 继承 Jinja2模板 配置 CSRF 原理 如何防范 一.Django使用自带模板 1.1 配置 在工程中创建模板目录templates.[然后新 ...

  3. 第三百一十节,Django框架,模板语言

    第三百一十节,Django框架,模板语言 模板语言就是可以将动态数据在html模板渲染的语言 一.接收值渲染 locals()函数,写在请求响应render()函数里,可以将逻辑处理函数里的变量传到h ...

  4. Django 笔记4 -- 模板

    Django 笔记4 – 模板 Django 系列笔记是笔者学习.实践使用 Django 的相关笔记,大量参考了知了课堂的<Django零基础到项目实战>教程. 参考文档: Django官 ...

  5. Django框架(23.Django中的模板的标签、变量、过滤器和注释)

    模板 作为Web框架,Django提供了模板,用于编写html代码,还可以嵌入模板代码更快更方便的完成页面开发,再通过在视图中渲染模板,将生成最终的html字符串返回给客户端浏览器.模版致力于表达外观 ...

  6. Django视图与模板+vs2019

    View视图,负责业务逻辑,并在适当的时候调用Model和Template http请求中产生的两个核心的对象:HttpRequest(http请求),HttpResponse(http响应) req ...

  7. Django的语言模板

    Django语言模板 一.变量(variables) 二.标签 (tags) 三.过滤器(filters) 四.模板文件的放置路径 a.项目模板 b.应用模板 五.模板的继承 六.模板文件中加载静态文 ...

  8. django自带模板使用及语法

    1 配置 在工程中创建模板目录templates. 在settings.py配置文件中修改TEMPLATES配置项的DIRS值: TEMPLATES = [{'BACKEND': 'django.te ...

  9. Django建站 - 模板篇

    上一节学会了怎么使用 django 创建项目,以及创建app,这次学习在一个app中使用网页模版. 一.模版语法规则 1.1.变量 : {{ var }}** 1.2.标签 : {% var %}** ...

最新文章

  1. 2021清华大学年度人物候选 | 曹丰泽:我要证明,理想主义的路是走得通的
  2. python 进程间通信效率_Python进程间通信 multiProcessing Queue队列实现详解
  3. mysql搭建主主_mysql主主配置
  4. 重温Android四大组件(一)—Activity的生命周期
  5. windows系统安装python模块
  6. c 和php 加密,加载由blenc加密的页面时出错(C和PHP代码)
  7. 总结 构造函数与非构造函数 原型继承的一个方法
  8. 知识点:Mysql 索引原理完全手册(1)
  9. [html] websocket握手阶段是通过什么协议传输的?
  10. C++ Vector 使用心得
  11. STM32F103xxx大容量增强型芯片之间有什么区别?(来自STM32神舟系列)
  12. 【机器学习-西瓜书】三、逻辑回归(LR);线性判别分析(LDA)
  13. Windows上的Spark环境搭建后,运行时报错的问题
  14. js整形转成double_那么,来用 JS 画个黑洞吧!
  15. 计算机应用基础全解,第三章习题-ddg全解.doc
  16. PTA——基础编程题 | 7-27 冒泡法排序 (20分)
  17. LAZADA四大行业最新趋势选品指南!菲律宾Bday大促活动报名
  18. 南研所前辈对华为的认识
  19. python unpacking_python packing unpacking 组包解包
  20. 浙江移动物联网应用开放平台(免费使用)

热门文章

  1. 团队第二次冲刺第一天
  2. Linux strace命令 一
  3. 连接Oracle9i,因字符集造成乱码的解决方法
  4. JDK1.5英文版CHM文档下载地址
  5. FPGA核心板内部各类型资源总结(xilinx)
  6. python--列表,元组,字符串互相转换
  7. silverlight项目工作小结
  8. 数据结构上机实践第11周项目1 - 图基本算法库
  9. (七)图像处理中常用算子Laplacian\Sobel\Roberts\Prewitt\Kirsch
  10. 图像处理随笔——非极大值抑制