Django的模板系统

为什么要有模板系统

来看以下代码

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

  返回文本的方式是不是有点特别,这种是将html直接硬编码在Python代码之中.

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

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

基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。

变量

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>

  

过滤器

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

  

标签

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

for标签

遍历元素

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

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

遍历一个字典

注:循环序号可以通过{{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 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

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

模板继承(母版)

{% load static %}
<!DOCTYPE html>

<html lang="zh-CN">
<head>
    <meta charset="utf-8" http-equiv="content-type">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" href="{% static 'imgs/layout/luffy-logo.png' %}">
    <title>CRM信息管理系统</title>
    <link href="{% static '/bootstrap-3.3.7/css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/dashboard.css' %}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'font-awesome-4.7.0/css/font-awesome.min.css' %}">
    {% block css %}

    {% endblock %}

</head>

<body>

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <img src="{% static  "imgs/layout/logo.svg" %}" alt=""
                 style="float: left;padding-top: 5px;padding-right: 5px">
            <a class="navbar-brand" href="#">CRM信息管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <div class="navbar-right">

                <img class="img-circle" height="45px" style="margin-top: 2.5px; margin-right: 5px"
                     src="{% static 'imgs/layout/default.png' %}" alt="" data-toggle="dropdown"
                     aria-haspopup="true" aria-expanded="false">
                <ul class="dropdown-menu">
                    <li><a href="#">个人中心</a></li>
                    <li><a href="#">修改密码</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">注销</a></li>
                </ul>
            </div>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">信息 <i class="fa fa-commenting-o" aria-hidden="true">&nbsp;</i><span
                        class="badge">4</span></a></li>
                <li><a href="#">通知 <i class="fa fa-envelope-o" aria-hidden="true">&nbsp;</i><span class="badge">4</span></a>
                </li>
                <li><a href="#">任务 <i class="fa fa-bell-o" aria-hidden="true">&nbsp;</i><span class="badge">4</span></a>
                </li>

            </ul>

        </div>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">

            <ul class="nav nav-sidebar">
                <li ><a href="{% url 'customer' %}">客户列表</a></li>
                <li ><a href="{% url 'my_customer' %}">我的客户</a></li>

                <li><a href="#">Analytics</a></li>
                <li><a href="#">Export</a></li>

            </ul>


        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">

            <div class="table-responsive">
               {% block content %}

               {% endblock %}
            </div>
        </div>
    </div>
</div>
<script src="{% static 'js/jQuery.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7/js/bootstrap.js' %}"></script>
{% block js %}

{% endblock %}

</body>
</html>
母版示例
{% extends 'base.html' %}
{% block css %}
    <style>
        th, td {
            text-align: center;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">客户信息</div>
        <a href="{% url 'add_customer' %}?{{ query_params }}" class="btn btn-primary btn-sm"
           style="margin-top: 5px;margin-left: 15px;padding-right: 3px;padding-left: 3px">添加</a>
{#        {{ add_btn }}#}
        <div class="panel-body">
            <div>
                <form action="" class="form-inline pull-right">
                    <input type="text" name="query" class="form-control">
                    <button class="btn btn-sm btn-primary">搜索 <i class="fa fa-search"></i></button>
                </form>
            </div>
            <form action="" method="post" class="form-inline">
                {% csrf_token %}
                <select name="action" class="form-control" style="margin: 5px 0">
                    <option value="">请选择</option>
                    <option value="multi_delte">删除</option>
                    <option value="multi_apply">放入私户</option>
                    <option value="multi_pub">放入公户</option>
                </select>
                <button class="btn btn-success btn-sm">提交</button>

                <table class="table table-bordered table-hover table-condensed">
                    <thead>
                    <tr>
                        <th>选择</th>
                        <th>序号</th>
                        <th>qq</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>电话</th>
                        <th>客户来源</th>
                        <th>咨询课程</th>
                        <th>班级类型</th>
                        <th>状态</th>
                        <th>咨询日期</th>
                        <th>最后跟进日期</th>
                        <th>销售</th>
                        <th>已报班级</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for customer in all_customer %}
                        <tr>
                            <td><input type="checkbox" name="id" value="{{ customer.id }}"></td>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ customer.qq }}</td>
                            <td>{{ customer.name|default:'暂无' }}</td>
                            <td>{{ customer.get_sex_display }}</td>
                            <td>{{ customer.phone|default:'暂无' }}</td>
                            <td>{{ customer.get_source_display }}</td>
                            <td>{{ customer.course }}</td>
                            <td>{{ customer.get_class_type_display }}</td>
                            <td>{{ customer.show_status }}</td>
                            <td>{{ customer.date }}</td>
                            <td>{{ customer.last_consult_date }}</td>
                            <td>{{ customer.consultant|default:'暂无' }}</td>
                            <td>{{ customer.show_Classes }}</td>
                            <td><a href="edit_customer/?id={{ customer.id }}"><i class="fa fa-edit fa-fw"></i></a></td>
                        </tr>
                    {% endfor %}


                    </tbody>
                </table>
            </form>

        </div>
        <div style="text-align: center">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    {{ pagination }}
                </ul>
            </nav>
        </div>

    </div>

{% endblock %}
相应的子模板示例

母版定义了一个简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。

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

extends 标签是这里的关键。它告诉模版引擎,这个模版“继承”了另一个模版

原文地址:https://www.cnblogs.com/luxiangyu111/p/9794080.html