寂寞的阿呆

导航

模板层template

继续之前的views,你可

能已经注意到我们例子中视图中返回的的方式有点特别。也就是说.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]})

模板语法之变量

在djgango模板中遍历复杂数据结构的的关键是句点字符.

语法:

{{var_name}}

views:

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:

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

{{ value|filesizeformat }}

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

date:

如果value= datetime.datetime.now()

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

slice:

如果value = 'hello world'

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

truncatechars:

如果字符串字符多余指定字符数量。那么会被截断。

参数:要截断的字符。

{{value|truncatechars:9}}

如果value是"Joel" 是 a  >,输出将为"Joel" i...

safe:

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

value = "<a href = "">点击</a>"


{{value|safe}}

这件简单介绍一些常用的模板过滤器:http://python.usyiyi.cn/translate/django_182/ref/templates/builtins.html#ref-templates-builtins-tags

模板之标签:

标签看起来是这样的:{%tag%}.标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到额外信息到模板中。

一些标签需要开始和结束标签(例如{%tag%})...标签内容..{%endtag%}

for标签:

遍历每一个元素:

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

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

遍历一个字典:

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

循环序号可以通过forloop显示

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 %}

 

posted on 2017-11-14 14:29  寂寞的阿呆  阅读(81)  评论(0)    收藏  举报