Django的模板系統

爲何要有模板系統

來看如下代碼css

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

  返回文本的方式是否是有點特別,這種是將html直接硬編碼在Python代碼之中.html

儘管這種技術便於解釋視圖是如何工做的,但直接將HTML硬編碼到你的視圖裏卻並非一個好主意。 讓咱們來看一下爲何:python

  • 對頁面設計進行的任何改變都必須對 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>

注意:句點符也能夠用來引用對象的方法(無參數方法):bootstrap

<h4>字典:{{ dic.name.upper }}</h4>

  

過濾器

default

  若是一個變量是false或者爲空,使用給定的默認值。不然,使用變量的值,如:緩存

{{ value|default:"nothing" }}

  

length

  返回值的長度。它對字符串和列表都起做用,如:安全

{{ value|length }}

  若是 value 是 ['a', 'b', 'c', 'd'],那麼輸出是 4。app

filesizeformat

  將值格式化爲一個 「人類可讀的」 文件尺寸 (例如 '13 KB''4.1 MB''102 bytes', 等等),如ide

{{ value|filesizeformat }}

若是 value 是 123456789,輸出將會是 117.7 MBsvg

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 標籤是這裏的關鍵。它告訴模版引擎,這個模版「繼承」了另外一個模版

相關文章
相關標籤/搜索