单独写一篇模板文件的样式,方便收藏使用。
其实这都是前端需要看的。。没法自己一个人都要搞!
内容替换:
HTML文件内容 polls/templates/polls/hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ hello }}</h1>
</body>
</html>
视图中替换 polls/urls.py
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = 'Hello World!'
return render(request, 'polls/hello.html', context)
路由中添加 polls/views.py
from django.urls import path
from . import views
urlpatterns = [
path('hello', views.hello, name='hello'),
]
效果展示:
基本语法格式如下:
{% if 条件 %}
... 内容
{% endif %}
或者:
{% if 条件1 %}
... 内容 1
{% elif 条件2 %}
... 内容 2
{% else %}
... 内容 3
{% endif %}
根据条件判断是否输出。if/else 支持嵌套。
{% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反( not ),例如:
{% if 条件1 and 条件2 %}
条件1 和 条件2 变量都是可用的。
{% endif %}
语法同Python类似。
{% for %} 允许我们在一个序列上迭代。
与Python的 for 语句的情形类似,循环语法是 for X in Y ,Y是要迭代的序列而X是在每一个特定的循环中使用的变量名称。
每一次循环中,模板系统会渲染在 {% for %} 和 {% endfor %} 之间的所有内容。
列入我们写的:
{% for i in list %}
<h1>{{h1}}</h1>
{% endfor %}
同样支持嵌套。
语法与Python 类似。
{% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
列子:
{% ifequal 变量1 变量2 %}
<h1>相等!</h1>
{% endifequal %}
和 {% if %} 类似, {% ifequal %} 支持可选的 {% else%} 标签:
{% ifequal 变量1 变量2 %}
<h1>不相等</h1>
{% else %}
<h1>相等</h1>
{% endifequal %}
Django 注释使用 {# #}。
{# 这是一个注释 #}
模板过滤器可以在变量被显示前修改它,过滤器使用管道字符,如下所示:
{{ name|lower }}
{{ name }} 变量被过滤器 lower 处理后,文档大写转换文本为小写。
过滤管道可以被* 套接* ,既是说,一个过滤器管道的输出又可以作为下一个管道的输入:
{{ my_list|first|upper }}
以上实例将第一个元素并将其转化为大写。
有些过滤器有参数。过滤器的参数跟随冒号之后并且总是以双引号包含。例如:
{{ bio|truncatewords:"30" }}
这个将显示变量 bio 的前30个词。
其他过滤器:
{{ pub_date|date:"F j, Y" }}
{% include %} 标签允许在模板中包含其它的模板的内容。
下面这个例子都包含了 nav.html 模板:
{% include "nav.html" %}
模板可以用继承的方式来实现复用。
我们继承之前的 hello.html 模板文件,然后新建一个继承模板:
我们要先修改hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ hello }}</h1>
{% block jc %}
<p>继承部分1</p>
{% endblock %}
{% block jcj %}
<p>继承部分2 没有继承 依旧显示</p>
{% endblock %}
</body>
</html>
以上代码中,名为 jc 和 jcj 的 block 标签是可以被继承者们替换掉的部分。
所有的 {% block %} 标签告诉模板引擎,子模板可以重载这些部分。
class_test.html 中继承 hello.html ,并替换特定 block,class_test .html修改后的代码如下:
{%extends "polls/hello.html" %}
{% block jc %}
<p>这里是继承 hello 文件后可以添加的部分</p>
<p> 萌海无涯 </p>
<p> {{ tt }} </p>
{% endblock %}
同样新建一个 视图
def class_test(request):
context = {'tt':'测试继承文件'}
return render(request, 'polls/class_test.html', context)
添加 url路由表
path('class_test', views.class_test, name='class_test'),
访问hello :
访问 class_test:
上面是没有替换 hello 里面的变量,我们给 hello 模板中的变量也传送进去,同样会给我们显示出来。
def class_test(request):
context = {'hello': 'Hello World!', 'tt':'测试继承文件'}
return render(request, 'polls/class_test.html', context)