这个函数有三个参数 −
请求− 初始化请求
模板路径 − 这是相对于在项目 settings.py 文件的变量到 template_dirs 选项的路径。
参数字典 − 字典包含所需的模板中的所有变量。这个变量可以创建或者可以使用 locals() 通过在视图中声明的所有局部变量。
变量显示如下:{{variable}}. 模板由视图在渲染(render)函数的第三个参数发送的变量来替换变量。让我们改变 hello.html 显示当天的日期 :
hello.html
<html> <body> hello world!!!<p>today is {{today}}</p> </body> </html>
def hello(request): today = datetime.datetime.now().date() return render(request, "hello.html", {"today" : today})
现在,我们将得到下面的输出在访问url /myapp/hello 之后−
hello world!!! today is sept. 11, 2015
正如你可能已经注意到,如果变量不是一个字符串,django会使用__str__方法来显示它;并以同样的原则,你可以访问对象的属性,就像在python中使用的一样。例如:如果我们想显示日期的年份,这里的变量是: {{today.year}}.
它们可以帮助您显示修改的变量。过滤器的结构如下所示: {{var|filters}}.
一个简单的实例 −
{{string|truncatewords:80}} − 过滤器将截断字符串,所以只看到前80个字符。
{{string|lower}} − 转换字符为小写
{{string|escape|linebreaks}} − 转义字符串内容,然后换行转换为标签。
标签可以执行以下操作:if 条件,for循环,模板继承以及更多。
就像在python中,你可以使用if,else和elif在模板中 −
<html> <body> hello world!!!<p>today is {{today}}</p> we are {% if today.day == 1 %} the first day of month. {% elif today == 30 %} the last day of month. {% else %} i don't know. {%endif%} </body> </html>
就像'if',我们有 'for' 标签,这些完全像在python中一样使用它们。让我们改变 hello视图列表发送到我们的模板 −
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 }} −
<html> <body> hello world!!!<p>today is {{today}}</p> we are {% if today.day == 1 %} the first day of month. {% elif today == 30 %} the last day of month. {% else %} i don't know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} </body> </html>
我们应该得到输出的内容如下 −
hello world!!! today is sept. 11, 2015 we are i don't know. mon tue wed thu fri sat sun
模板系统是不完整模板继承。当您设计模板的含义,子模板会根据自己的需要填写一个主模板,就像一个页面中所选选项卡可能需要一个特殊的css。
main_template.html
<html> <head> <title> {% block title %}page title{% endblock %} </title> </head> <body> {% block content %} body content {% endblock %} </body> </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 == 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,我们仍然会得到相同的结果和以前一样,但现在我们靠的是扩展,并不用重构代码-−
在 main_template.html 我们定义使用标签块。标题栏块将包含页面标题,以及内容块将在页面主内容。在home.html中使用扩展继承来自main_template.html,那么我们使用上面块定义(内容和标题)。
注释标签用来模板定义注释,不是html注释,它们将不会出现在html页面。它可以是一个文件或只是注释一行代码。