python测试开发django-5.模板templates

前言

html是一个静态的语言,里面没法传一些动态参数,也就是一个写死的html页面。如果想实现在一个固定的html样式,传入不同的参数,这就可以用django的模板传参来解决。

模板参数

先在hello应用下新建一个templates文件夹,层级目录如下

└─helloworld
    │  db.sqlite3
    │  manage.py │ __init__.py │ ├─hello │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├─migrations │ │ │ __init__.py │ │ │ ├─templates │ │ yoyo.html │ │ __init__.py │ └─helloworld │ settings.py │ urls.py │ wsgi.py │ __init__.py

新建一个yoyo.html文件,hello/templates/yoyo.html文件内容如下,模板变量用{{变量名称}}来表示

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>上海-悠悠</title> </head> <body> <h1>hello world! {{name}}同学</h1> </body> </html>

在settings.py脚本里面添加模板的路径,修改TEMPLATES 中的 DIRS 为[BASE_DIR+"/hello/templates",]
BASE_DIR的值前面已经定义为当前脚本的路径:os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/hello/templates",],   # 默认为[] 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]

视图与url

hello/views写个视图函数,内容如下

from django.http import HttpResponse, Http404

# Create your views here.

def yoyo(request): context = {} context['name'] = '悠悠' return render(request, 'yoyo.html', context)

helloworld/urls.py添加访问路径

from django.conf.urls import url
from django.urls import re_path, path
from hello import views urlpatterns = [ path("yoyo/", views.yoyo), ]

接着在浏览器输入地址:http://127.0.0.1:8000/yoyo/ 就能访问了

Django 模板标签

if/else 标签

条件判断if语句,最后endif结束

{% if condition1 %} ... display 1 {% elif condition2 %} ... display 2 {% else %} ... display 3 {% endif %}

for 标签

与Python的 for 语句的情形类似,循环语法是 for X in Y ,Y是要迭代的序列而X是在每一个特定的循环中使用的变量名称。

每一次循环中,模板系统会渲染在 {% for %} 和 {% endfor %} 之间的所有内容。

<ul>
{% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>

ifequal/ifnotequal 标签

{% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
下面的例子比较两个模板变量 user 和 currentuser :

{% ifequal user currentuser %} <h1>Welcome!</h1> {% endifequal %}

和 {% if %} 类似, {% ifequal %} 支持可选的 {% else%} 标签

{% ifequal section 'sitenews' %} <h1>Site News</h1> {% else %} <h1>No News Here</h1> {% endifequal %}

注释标签

Django 注释使用 {# #}。

{# 这是一个注释 #}

猜你喜欢

转载自www.cnblogs.com/mashuqi/p/10972354.html