Django之模板层的实现代码


Posted in Python onSeptember 09, 2019

在例子视图中返回文本的方式有点特别,即HTML被直接硬编码在Python代码之中。

def current_datetime(request):
  now = datetime.datetime.now()
  html = "<html><body>It is now %s.</body></html>" % now
  return HttpResponse(html)

尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并是一个好主意。让我们来看一下为什么:

  • 对页面设计进行的任何改变都必须对Python代码进行相应的修改。站点设计的修改往往比底层Python代码的修改要频繁得多,因此如果可以在不进行Python代码修改的情况下变更设计,将会方便很多。
  • Python代码编写和HTML设计是两项不同的工作,大多数专业的网站开发环境都将他们分配给不同的人员(甚至不同的部门)来完成。设计者和HTML/CSS的编码人员不应该被要求去编辑Python的代码来完成他们的工作。
  • 程序员编写Python代码和设计人员制作模板两项工作过同时进行的额效率是最高的,远胜于让一个人等待另一个人完成对某个既包含Python又包含HTML的文件的编辑工作。

基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。我们可以使用Django的模板系统(Template System)来是现在这种模式,这就是本章要具体讨论的问题。

Python的模板:HTML代码 + 模板语法

def current_time(req):
  # ================================原始的视图函数
  # import datetime
  # now=datetime.datetime.now()
  # html="<html><body>现在时刻:<h1>%s.</h1></body></html>" %now

  # ================================django模板修改的视图函数
  # from django.template import Template,Context
  # now=datetime.datetime.now()
  # t=Template('<html><body>现在时刻是:<h1>{{current_date}}</h1></body></html>')
  # #t=get_template('current_datetime.html')
  # c=Context({'current_date':str(now)})
  # html=t.render(c)
  #
  # return HttpResponse(html)

  #另一种写法(推荐)
  import datetime
  now=datetime.datetime.now()
  return render(req, 'current_datetime.html', {'current_date':str(now)[:19]})

一、模板语法之变量

在Django模板中遍历复杂数据结构的关键是句点字符,语法:

{{var_name}}

views.py:

def index(request):
  import datetime
  s="hello"
  l=[111,222,333]  # 列表
  dic={"name":"yuan","age":18} # 字典
  date = datetime.date(1993, 5, 2)  # 日期对象

  class Person(object):
    def __init__(self,name):
      self.name=name

  person_yuan=Person("yuan") # 自定义类对象
  person_egon=Person("egon")
  person_alex=Person("alex")

  person_list=[person_yuan,person_egon,person_alex]

   return render(request,"index.html",{"l":l,"dic":dic,"date":date,"person_list":person_list})

template:

<h4>{{s}}</h4>
<h4>列表:{{ l.0 }}</h4>
<h4>列表:{{ l.2 }}</h4>
<h4>字典:{{ dic.name }}</h4>
<h4>日期:{{ date.year }}</h4>
<h4>类对象列表:{{ person_list.0.name }}</h4>
注:句点符也可以用来引用对象的方法(无参数方法):
<h4>字典:{{ dic.name.upper }}</h4>

二、模板之过滤器

语法:

{{obj|filter_name:param}}

default

如果一个变量是False后者为空,使用给定的默认值。否则,使用变量的值。例如:

{{ value|default:'nothing' }}

length

返回值的长度。它对字符串和列表都起作用。例如:

{{ value|length }}

如果value是 ['a', 'b', 'c', 'd'] ,那么输出的就是4.

filesizeformat

将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB' , '4.1 MB' , '102 bytes' , 等等)。例如:

{{ value|filesizeformat }}

如果value = 123456789,输出将会是117.7 MB。

date

如果value = datetime.datetime.now()

{{ value|date:"Y-m-d" }}

slice

如果value = "hello world"

{{ value|slice:"2:-1" }}

truncatechars

如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列("...")结尾。

参数:要截断的字符数

{{ value|truncatechars:9 }}

safe

Django的模板中会对HTML标签和JS语法等标签进行自动转义,原因显而易见这样是为了安全。但是有时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后他添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器"|safe"的方式告诉Django这段代码是安全的不必转义。比如:

value = "<a href=''>点击</a>"
{{ value|safe }}

三、模板之标签

标签看起来像是这样: {% tag %} 。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息的模板中。一些标签需要开开始和结束标签(例如 {% tag %} ...标签 内容... {% endtag %} )。

for标签

遍历每一个元素:

可以利用 {% for obj in list reversed %} 方向完成循环。

遍历一个字典:

{% for key,val in dic.items %}
  <p>{{ key }}:{{ val }}</p>
{% endfor %}

注:循环序号可以通过 {{ for|loop }} 显示

forloop.counter      # The current iteration of the loop (1-indexed)
forloop.counter0     # The current iteration of the loop (0-indexed)
forloop.revcounter    # The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0    # The number of iterations from the end of the loop (0-indexed)
forloop.first       # True if this is the first time through the loop
forloop.last       # True if this is the last time through the loop
for ... empty

for标签带有一个可选的 {% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %}
  <p>{{ person.name }}</p>

{% empty %}
  <p>sorry,no person here</p>
{% endfor %}

if 标签

{% if %} 会对一个变量求值,如果它的值是True(存在、不为空、且不是boolean类型的False值),对应的内容块会输出。

{% if num > 100 or num < 0 %}
  <p>无效</p>
{% elif num > 80 and num < 100 %}
  <p>优秀</p>
{% else %}
  <p>凑活吧</p>
{% endif %}

with 标签

使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵”的方法(比如访问数据库)很多次的时候是非常有用的。例如:

{% with total=business.employees.count %}
  {{ total }} employee{{ total|pluralize }}
{% endwith %}

csrf_token 标签

这个标签用于跨站请求伪造保护。

四、自定义标签和过滤器

1、在settings中的INSTALLED_APPS配置当前app,不然Django无法找到自定义的simple_tag。

2、在app中创建templatetags模块(模块名只能是templatetags)。

3、创建任意 .py 文件,如:my_tags.py。

from django import template
 from django.utils.safestring import mark_safe
 register = template.Library()  #register的名字是固定的,不可改变 
 @register.filter
 def filter_multi(v1,v2):
   return v1 * v2
 <br>
 @register.simple_tag
 def simple_tag_multi(v1,v2):
   return v1 * v2
 <br>
 @register.simple_tag
 def my_input(id,arg):
   result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
   return mark_safe(result)

4、在使用自定义simple_tag和filter的HTML文件中导入之前创建的my_tags.py。

{% load my_tags %}

5、使用simple_tag和filter(如何调用)

-------------------------------.html
 {% load xxx %}    
 # num=12
 {{ num|filter_multi:2 }} #24
 {{ num|filter_multi:"[22,333,4444]" }}
 {% simple_tag_multi 2 5 %} 参数不限,但不能放在if for语句中
 {% simple_tag_multi num 5 %}
注:filter可以用在if等语句后,simpe_tag不可以。
{% if num|filter_multi:30 > 100 %}
  {{ num|filter_multi:30 }}
{% endif %}

五、模板继承(extend)

Django模板引擎中最强大也是最复杂的部分就是模板继承了。模板继承可以让你创建一个基本的“骨架”模板,它包含你站点中的全部元素,并且可以定义能够被子模板覆盖的blocks.

通过从下面这个例子开始,可以容易地理解模板继承:

<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="style.css" rel="external nofollow" rel="external nofollow" />
  <title>{% block title %}My amazing site{%/span> endblock %}</title>
</head>

<body>
  <div id="sidebar">
    {% block sidebar %}
    <ul>
      <li><a href="/" rel="external nofollow" rel="external nofollow" >Home</a></li>
      <li><a href="/blog/" rel="external nofollow" rel="external nofollow" >Blog</a></li>
    </ul>
    {% endblock %}
  </div>

  <div id="content">
    {% block content %}{% endblock %}
  </div>
</body>
</html>

假设这个模板叫做 base.html,它定义了一个可以用于两列排版页面的简单HTML骨架。“字模板”的工作是用它们的内容填充的blocks。

在这个例子中,block标签定义了三个可以被子模板内容填充的block。block告诉模板引擎:子模板可能会覆盖掉模板中的这些位置。

子模板可能看起来是这样的:

{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
  <h2>{{ entry.title }}</h2>
  <p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}

extends标签是这里的关键。它告诉模板引擎,这个模板“继承”了另一个模板。当模板系统处理这个模板时,首先,它将定位父模板——在此例中,就是 base.html。

那时,模板引擎将注意到 base.html 中的三个block标签,并用子模板中的内容来替换这些block。根据blog_entries的值,输出可能看起来是这样的:

<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="style.css" rel="external nofollow" rel="external nofollow" />
  <title>My amazing blog</title>
</head>

<body>
  <div id="sidebar">
    <ul>
      <li><a href="/" rel="external nofollow" rel="external nofollow" >Home</a></li>
      <li><a href="/blog/" rel="external nofollow" rel="external nofollow" >Blog</a></li>
    </ul>
  </div>

  <div id="content">
    <h2>Entry one</h2>
    <p>This is my first entry.</p>

    <h2>Entry two</h2>
    <p>This is my second entry.</p>
  </div>
</body>
</html>

请注意,子模版并没有定义 sidebar block,所以系统使用了父模版中的值。父模版的 {% block %} 标签中的内容总是被用作备选内容(fallback)。这种方式使代码得到最大程度的复用,并且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。

下面是使用继承的一些提示:

  • 如果你在模版中使用 {% extends %} 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。
  • 在base模版中设置越多的 {% block %} 标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。
  • 如果你发现你自己在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 {% block %} 中。
  • If you need to get the content of the block from the parent template, the variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.

为了更好的可读性,你也可以给你的 {% endblock %} 标签一个 名字 。例如:

{% block content %}
...
{% endblock content %}

在大型模板中,这个方法帮你清楚地看到哪一个 {% block %} 标签被关闭了。

不能在一个模版中定义多个相同名字的 block 标签。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python为tornado添加recaptcha验证码功能
Feb 26 Python
python爬虫的工作原理
Mar 05 Python
python实现用户答题功能
Jan 17 Python
详解Python logging调用Logger.info方法的处理过程
Feb 12 Python
python爬虫租房信息在地图上显示的方法
May 13 Python
python中PS 图像调整算法原理之亮度调整
Jun 28 Python
opencv python 图像轮廓/检测轮廓/绘制轮廓的方法
Jul 03 Python
python数据类型之间怎么转换技巧分享
Aug 20 Python
Python reques接口测试框架实现代码
Jul 28 Python
Django模板报TemplateDoesNotExist异常(亲测可行)
Dec 18 Python
python实现计算图形面积
Feb 22 Python
详解OpenCV曝光融合
Apr 29 Python
Django模板语言 Tags使用详解
Sep 09 #Python
Python中turtle库的使用实例
Sep 09 #Python
Django之路由层的实现
Sep 09 #Python
python中web框架的自定义创建
Sep 08 #Python
python web框架中实现原生分页
Sep 08 #Python
python中open函数的基本用法示例
Sep 07 #Python
Python3显示当前时间、计算时间差及时间加减法示例代码
Sep 07 #Python
You might like
php结合js实现点击超链接执行删除确认操作
2014/10/31 PHP
Mac下快速搭建PHP开发环境步骤详解
2019/05/05 PHP
JS判断是否为数字,是否为整数,是否为浮点数的代码
2010/04/24 Javascript
如何判断元素是否为HTMLElement元素
2013/12/06 Javascript
精通JavaScript的this关键字
2020/05/28 Javascript
AngularJS验证信息框架的封装插件用法【w5cValidator扩展插件】
2016/11/03 Javascript
Jquery Easyui进度条组件Progress使用详解(8)
2020/03/26 Javascript
详解handlebars+require基本使用方法
2016/12/21 Javascript
React Native如何消除启动时白屏的方法
2017/08/08 Javascript
代码详解javascript模块加载器
2018/03/04 Javascript
jQuery实现点击图标div循环放大缩小功能
2018/09/30 jQuery
express express-session的使用小结
2018/12/12 Javascript
layui递归实现动态左侧菜单
2019/07/26 Javascript
Vue搭建后台系统需要注意的问题
2019/11/08 Javascript
用Node写一条配置环境的指令
2019/11/14 Javascript
微信小程序保存图片到相册权限设置
2020/04/09 Javascript
Python实现统计代码行的方法分析
2017/07/12 Python
python实现比较文件内容异同
2018/06/22 Python
python3中使用__slots__限定实例属性操作分析
2020/02/14 Python
Python读取VOC中的xml目标框实例
2020/03/10 Python
如何使用Pytorch搭建模型
2020/10/26 Python
中国排名第一的外贸销售网站:LightInTheBox.com(兰亭集势)
2016/10/28 全球购物
四川internet信息高速公路(C#)笔试题
2012/02/29 面试题
DTD的含义以及作用
2014/01/26 面试题
财务工作个人求职的自我评价
2013/12/19 职场文书
小学生家长评语大全
2014/02/10 职场文书
2014年十一国庆向国旗敬礼寄语
2014/04/11 职场文书
工伤劳动仲裁代理词
2015/05/25 职场文书
于丹讲座视频观后感
2015/06/15 职场文书
保险公司2016开门红口号集锦
2015/12/24 职场文书
2016先进工作者事迹材料
2016/02/25 职场文书
Python实战之实现简易的学生选课系统
2021/05/25 Python
Python数据可视化之基于pyecharts实现的地理图表的绘制
2021/06/10 Python
源码解读Spring-Integration执行过程
2021/06/11 Java/Android
python实现简单聊天功能
2021/07/07 Python
详解python的异常捕获
2022/03/03 Python