Django 简明教程

Django - Template System

Django 使得可以将 Python 和 HTML 分开,Python 用于视图,HTML 用于模板。为了将两者关联,Django 依靠 render 函数和 Django 模板语言。

Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language.

The Render Function

此函数需要三个参数 −

This function takes three parameters −

  1. Request − The initial request.

  2. The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.

  3. Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.

Django Template Language (DTL)

Django 的模板引擎提供了一种迷你语言来定义应用程序面向用户的层。

Django’s template engine offers a mini-language to define the user-facing layer of the application.

Displaying Variables

变量看起来像这样:{{variable}}。模板使用 render 函数的第三个参数中视图发送的变量替换可变对象。我们来更改 hello.html 以显示今天的日期 −

A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let’s change our hello.html to display today’s date −

hello.html

hello.html

<html>

   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>

</html>

然后我们的视图更改为 −

Then our view will change to −

def hello(request):
   today = datetime.datetime.now().date()
   return render(request, "hello.html", {"today" : today})

现在我们访问 URL/myapp/hello 后将获得以下输出 −

We will now get the following output after accessing the URL/myapp/hello −

Hello World!!!
Today is Sept. 11, 2015

您可能已经注意到,如果变量不是字符串,Django 会使用 str 方法来显示它;而且使用相同原则,您可以访问对象属性,就像在 Python 中所做的那样。例如:如果我们想要显示日期年份,我的变量将为:{{ today.year }}。

As you have probably noticed, if the variable is not a string, Django will use the str method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}.

Filters

它们帮助您在显示时间修改变量。过滤器结构如下所示:{{ var|filters }}。

They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.

Some examples

Some examples

  1. {{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words.

  2. {{string|lower}} − Converts the string to lowercase.

  3. {{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags.

您还可以设置变量的默认值。

You can also set the default for a variable.

Tags

标签允许您执行以下操作:if 条件、for 循环、模板继承等。

Tags lets you perform the following operations: if condition, for loop, template inheritance and more.

Tag if

就像在 Python 中一样,您可以在模板中使用 if、else 和 elif −

Just like in Python you can use if, else and elif in your template −

<html>
   <body>

      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}

      the first day of month.
      {% elif today.day == 30 %}

      the last day of month.
      {% else %}

      I don't know.
      {%endif%}

   </body>
</html>

在此新模板中,根据日期,模板将呈现特定值。

In this new template, depending on the date of the day, the template will render a certain value.

Tag for

就像“if”一样,我们有“for”标签,它的工作原理与 Python 中完全相同。让我们更改 hello 视图以将列表传输到我们的模板 −

Just like 'if', we have the 'for' tag, that works exactly like in Python. Let’s change our hello view to transmit a list to our template −

def hello(request):
   today = datetime.datetime.now().date()

   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})

使用 {{ for }} 显示该列表的模板 −

The template to display that list using {{ for }} −

<html>
   <body>

      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}

      the first day of month.
      {% elif today.day == 30 %}

      the last day of month.
      {% else %}

      I don't know.
      {%endif%}

      <p>
         {% for day in days_of_week %}
         {{day}}
      </p>

      {% endfor %}

   </body>
</html>

我们应该得到类似 −

And we should get something like −

Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun

Block and Extend Tags

如果没有模板继承,模板系统将无法完成。也就是说,在设计模板时,应该有一个带有孔的主模板,子模板将根据其需要进行填充,就像一个页面可能需要一个特殊 css 来突出显示所选选项卡。

A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child’s template will fill according to his own need, like a page might need a special css for the selected tab.

让我们更改 hello.html 模板来继承自 main_template.html。

Let’s change the hello.html template to inherit from a main_template.html.

main_template.html

main_template.html

<html>
   <head>

      <title>
         {% block title %}Page Title{% endblock %}
      </title>

   </head>

   <body>

      {% block content %}
         Body content
      {% endblock %}

   </body>
</html>

hello.html

hello.html

{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today.day == 30 %}

the last day of month.
{% else %}

I don't know.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}

在上面的示例中,调用 /myapp/hello 时,我们将仍然获得与以前相同的结果,但现在我们依靠 extends 和 block 来重构我们的代码 −

In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code −

在 main_template.html 中,我们使用标签 block 来定义块。title 块将包含页面标题,而 content 块将包含页面主要内容。在 home.html 中,我们使用 extends 来从 main_template.html 继承,然后我们填充上述定义的块(内容和标题)。

In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title).

Comment Tag

标签 comment 有助于在模板中定义注释,而不是 HTML 注释,它们不会显示在 HTML 页面中。它可以用来记录文档或仅仅注释一行代码。

The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code.