django模板_Django模板

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>" % today
    return 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 file

    html文件的路径
  • 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 url

from . import views

urlpatterns = [
    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 HttpResponse

from 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:

django python templates run on localhost

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

The output in your web browser should be like:

django template tutorial output

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

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应用程序将准备就绪。

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

django模板

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值