Django语言模板

  • 一、变量(variables)
  • 二、标签 (tags)
  • 三、过滤器(filters)
  • 四、模板文件的放置路径
    • a、项目模板
    • b、应用模板
  • 五、模板的继承
  • 六、模板文件中加载静态文件
  • 七、具体代码展示
    • a、传递一个字典
    • b、table表格加载
    • c、ul列表加载数据
  • 八、总结

一、变量(variables)

模板中的变量一般使用双括号``包围。在模板中你可以使用.获取一个变量(字典、对象和列表)的属性,如:

    {{ my_dict.key }}  {{ my_object.attribute }}{{ my_list.0 }}

二、标签 (tags)

Django的标签(tags)用双%括号包裹,常用Django标签包括:

# 内容块
{% block content %} 代码块 {% endblock %}# 防csrf攻击
{% csrf_token %} 表单专用# for循环
<ul> {% for athlete in athlete_list %}   <li>{{ forloop.counter }} - {{ athlete.name }}</li> {% empty %}   <li>Sorry, no athletes。</li> {% endfor %}
</ul># if判断
{% if title == "python" %} Say python.
{% elif title == "django"}Say django.
{% elif title == "django"}Say django.
{% else %}Say java.
{% endif %} # url反向解析
{% url 'blog:article_detail' article.id %}# with
{% with total=business.employees.count %}   {{ total }} employee{{ total|pluralize }}
{% endwith %}# 载入模板标签过滤器
{% load sometags_library %}# 模板包含
{% include "header.html" %}# 模板继承
{% include "base.html" %}# 获取当前时间now
{% now "jS F Y H:i" %}

三、过滤器(filters)

在模板中你可以使用过滤器(filter)来改变变量在模板中的显示形式。比如{{ article.title | lower }}中lower过滤器可以让文章的标题转化为小写。Django的模板提供了许多内置过滤器,你可以直接使用,非常方便。

项目 Value
lower, upper {{ article.title / lower }} 大小写
length {{ name /length }} 长度
default {{ value/default: “0” }} 默认值
date {{ picture.date / date:”Y-m-j “ }} 日期格式
dicsort {{ value /dicsort: “name” }} 字典排序
escape {{ title /escape }} 转义
filesizeformat {{ file/ filesizeformat }} 文件大小
first, last {{ list / first }} 首或尾
floatformat {{ value / floatformat }} 浮点格式
get_digit {{ value / get_digit }} 位数
join {{ list / join: “,” }} 字符连接
make_list {{ value / make_list }} 转字符串
pluralize {{ number / pluralize }} 复数
random {{ list / random }} 随机
slice {{ list /slice: “:2” }} 切
slugify {{ title /slugify }} 转为slug
striptags {{ body / striptags }} 去除tags
time {{ value / time: “H:i” }} 时间格式
timesince {{ pub_date / timesince: given_date }}
truncatechars {{ title / truncatechars: 10 }}
truncatewords {{ title / truncatewords: 2 }}
truncatechars_html {{ title /truncatechars_html: 2 }}
urlencode {{ path / urlencode }} URL转义
wordcount {{ body / wordcount }} 单词字数

四、模板文件的放置路径

模板文件有两种, 一种是属于整个项目(project)的模板,一种是属于某个应用(app)的模板。模板文件的放置路径必需正确, 否则Django找不到模板容易出现TemplateDoesNotExist的错误。

a、项目模板

项目模板
属于项目的模板文件路径一般是项目根目录下的templates文件夹。除此以外, 你还需要在settings.py种显示地将模板目录设置为BASE_DIR目录下的templates文件夹。

TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR, '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',],},},
]

b、应用模板

属于单个应用的模板文件路径一般是app目录下的app/templates/app文件夹, 这样做的好处是可以避免模板命名冲突。

下图以博客项目为例展示了项目模板文件和应用模板文件正确的存放路径。

myproject/ # 项目名manage.pymyproject/__init__.pyurls.pywsgi.pysettings.pyblog/ # 应用名__init__.pymodels.pymanagers.pyviews.pyurls.pytemplates/ # 应用模板文件blog/base.htmllist.htmldetail.htmltemplates/ # 项目模板文件base.htmlindex.htmlrequirements/base.txtdev.txttest.txtprod.txt
# 指定项目模板
return render(request, "index.html", { "msg": "hello world!",})# 指定应用模板
return render(request, "blog/list.html", { "articles": articles,})

五、模板的继承

Django支持模板的继承。你需要使用extends标签。在下面经典模板继承案例中,index.html继承了base.html的布局,如sidebar和footer,但是content模块会替换掉base.html中的content模块。

# base.html{% block sidebar %}
{% endblock %}{% block content %}
{% endblock %}{% block footer %}
{% endblock %}# index.html
{% extends "base.html" %}
{% block content %}{{ some code }}
{% endblock }

extends标签支持相对路径,这就意味着当文件夹结构如下所示时:

dir1/index.htmlbase2.htmlmy/base3.html
base1.html

模板index.html使用以下继承方式都是可以的。.号代表当前目录, …代表上层目录.

{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}

六、模板文件中加载静态文件

在模板文件我们要经常需要加载静态文件如css文件和js文件,操作方式如下所示:

第一步: 在myproject/settings.py设置静态文件目录STATIC_URL, 默认为static, 其作用是告诉Django静态文件会存放在各app下的static目录里。同时你还需确保django.contrib.staticfiles已经加入到INSTALLED_APPS里去了.

STATIC_URL = '/static/'

第二步: 先在你的app目录下新建一个static文件夹,然后再建一个app子目录,放入你需要的静态文件, 此时静态文件路径变为app/static/app/custom.css或则app/static/app/main.js

如果你需要使用的静态文件不属于某个app,而属于整个项目project,那么你还可以通过STATICFILES_DIRS定义静态文件文件夹列表。假设属于整个项目的静态文件放在根目录下的static文件夹和/var/www/static/里,那么myproject/settings.py可以加入下面两行代码:

STATICFILES_DIRS = [BASE_DIR / "static",'/var/www/static/',
]

第三步:在你的html模板里使用static标签,首先得载入这个标签, 如下所示:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %} Django Web Applications {% endblock %} </title><link rel="stylesheet" href="{% static 'app/custom.css' %}"><script type='text/javascript' src="{% static 'app/main.js' %}"></script>
</head>

注意:load static需要放在html的头部位置。如果extends标签和load同时存在,extends需要放在最上面,然后再放load等标签。

七、具体代码展示

a、传递一个字典

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context# Create your views here.
def index(request):dirct={"name":'huitao',"age":18,"gender":"男"}return render(request,"index.html",{"name":dirct})

index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试python的语言模板</title>
</head>
<body><span>{{name}}</span>
</body>
</html>

url:

from django.contrib import admin
from django.urls import path
from httLos_ import views as httLos_viewsurlpatterns = [path('admin/', admin.site.urls),path('', httLos_views.index),]

展示效果:

b、table表格加载

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Contextdef tableTest(request):asset_list=[{"id":123,"hostname":"huitao","creat_time":"2028-17","update_time":"2020-12-3"},{"id":123,"hostname":"huitao","creat_time":"2028-17","update_time":"2020-12-3"},{"id":123,"hostname":"huitao","creat_time":"2028-17","update_time":"2020-12-3"}]return render(request,'table.html', {'data': asset_list, 'user': 'huitao'})

table.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>{{ user }}</h1><table border="1" style="width: 1200px;height: 600px;text-align: center"><tr><th colspan="4" id="tg">{{ user }}</th></tr><tr><th>id编号</th><th>主机名称</th><th>创建时间</th><th>更新时间</th></tr>{% for item in data %}<tr><td>{{ item.id }}</td><td>{{ item.hostname }}</td><td>{{ item.creat_time }}</td><td>{{ item.update_time }}</td></tr>{% endfor %}</table>
</body>
</html>

url.py

from django.contrib import admin
from django.urls import path
from httLos_ import views as httLos_viewsurlpatterns = [path('admin/', admin.site.urls),path('tableTest/', httLos_views.tableTest),]

效果展示:

c、ul列表加载数据

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, Context# Create your views here.def liTest(request):content=["橘子","苹果","柿子","高果"]# 获取模板对象template = loader.get_template('ul.html')# 渲染模板, 得到标准的html内容html_str = template.render({"item_list":content}, request)# 响应请求,返回html界面return HttpResponse(html_str)

ul.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<ul>
<div>{{ item_list }}</div>{% for item in item_list %}<li>{{ item }}</li>{% endfor %}
</ul>{% for item in item_list %}
<p>{{ item }}</p>
{% endfor %}
</body>
</html>

url.py

from django.contrib import admin
from django.urls import path
from httLos_ import views as httLos_viewsurlpatterns = [path('admin/', admin.site.urls),path('liTest/', httLos_views.liTest),
]

效果展示:

八、总结

Django的学习起来还是很有乐趣,今天又花了俩个小时吧django学习了一下,从后端编写程序到前端展示,java的前后端现在慢慢分离了,django还是分离了比较好,这样展示数据还是比较死板
期待有更多的技术能让django强大起来。

主要参考地址:https://pythondjango.cn/django/basics/9-templates-filters-tags/

Django的语言模板相关推荐

  1. 第三百一十节,Django框架,模板语言

    第三百一十节,Django框架,模板语言 模板语言就是可以将动态数据在html模板渲染的语言 一.接收值渲染 locals()函数,写在请求响应render()函数里,可以将逻辑处理函数里的变量传到h ...

  2. Django框架(23.Django中的模板的标签、变量、过滤器和注释)

    模板 作为Web框架,Django提供了模板,用于编写html代码,还可以嵌入模板代码更快更方便的完成页面开发,再通过在视图中渲染模板,将生成最终的html字符串返回给客户端浏览器.模版致力于表达外观 ...

  3. django 1.8 官方文档翻译:4-2-1 Django模版语言

    Django模版语言 本文将介绍Django模版系统的语法.如果您需要更多该系统如何工作的技术细节,以及希望扩展它,请浏览 The Django template language: for Pyth ...

  4. Django建站 - 模板篇

    上一节学会了怎么使用 django 创建项目,以及创建app,这次学习在一个app中使用网页模版. 一.模版语法规则 1.1.变量 : {{ var }}** 1.2.标签 : {% var %}** ...

  5. django之template模板层-60

    django之template模板层-60 一.模板语言的变量 views.py def index(request): #模板语言的变量 name = 'Yven' addr = False age ...

  6. Django 笔记4 -- 模板

    Django 笔记4 – 模板 Django 系列笔记是笔者学习.实践使用 Django 的相关笔记,大量参考了知了课堂的<Django零基础到项目实战>教程. 参考文档: Django官 ...

  7. PhpStorm 超强语言模板的支持

    PhpStorm 超强语言模板的支持 原文:[转]PhpStorm 超强语言模板的支持 最近遇到一些PhpStorm编程的问题: 在使用Zen Coding插件时,PHPStorm不像Notepad+ ...

  8. Django Template 网页模板(五)

    Django Template 网页模板 6. Template 网页模板 6.1 Templeate 基础知识 6.2 Templeate 小案例 6.3 Template 标签 6. Templa ...

  9. (update)Django套用现成模板,导入html, css,js,images等文件

    (update)Django套用现成模板,导入html,css,js,images等文件 1/环境 Mac pycharm community2019.1 python3.7.3 2/参考资料 htt ...

最新文章

  1. mariadb 基础使用
  2. unittest ResourceWarning: unclosed socket.socket fd=864, family=AddressFamily.AF_INET... 解决办法...
  3. Emacs基础命令整理 - Unplugged - 博客频道 - CSDN.NET
  4. Introduction to the Trusted Services Project
  5. mysql错误1451_mysql错误代号-J(1451~1494)
  6. Python 空值与非空值
  7. 浅谈:Android应用清理内存
  8. 【转】2.3async中必须始终返回Task(@Ron.liang)
  9. SQL 语句执行顺序
  10. BZOJ 1878: [SDOI2009]HH的项链 | 莫队
  11. java linkedlist源码分析_LinkedList源码分析(基于Java8)
  12. Android开源库--ActiveAndroid(active record模式的ORM数据库框架)
  13. 检测到无效的异常处理程序例程。_异常控制流(1):异常概述和基本类型
  14. Redis内存分配简单分析
  15. (转)贝莱德,从0到6万亿
  16. java基本数据类型转类对象
  17. windows vcpkg下载慢
  18. 发送速率(传输速率)和传播速率
  19. 【学习体会】Lighttools8.4.0:简单光学系统实例
  20. 嵌入式了解 以及学习路线

热门文章

  1. 阶段1 - 03. 常用API第一部分 - 04. ArrayList集合
  2. python ccf题解 201809-1 卖菜
  3. icp许可证怎么申请
  4. 请将磁盘插入‘‘U盘(F:)‘‘的解决方法
  5. 网站推广第一周总结和反思
  6. 义隆单片机学习笔记之(二) 指令系统
  7. 国内知名MCU厂商官网整理
  8. 程序猿想平稳度过35岁中年危机?不妨试着考个研
  9. 人脸识别摄像头开发板和模组选型
  10. 使用Python实现12306自动化抢票