手機網(wǎng)站制作與建設(shè)百度收錄網(wǎng)址提交
模板之變量
所有的數(shù)據(jù)類型都可以在模板中使用
render(request, 'index.html', context={''})
render(request, 'index.html', context=locals())
"""在模板中使用變量的時候,用的是字典的key值,key值value值一般保持一致"""詳細請看上一篇末尾
模版之過濾器
語法
{{obj|filter__name:param}} 變量名字|過濾器名稱:變量
類似于函數(shù),函數(shù)才可以傳遞參數(shù)
語法:
?? ?{{ obj|過濾器:參數(shù) }}
過濾器:
????default
? ? length
? ? filesizeformat
? ? date
? ? trancatechars
? ? slice
? ? safe
? ? mark_safe # 導入
default
如果一個變量是false或者為空,使用給定的默認值。否則,使用變量的值。例如:
{{ value|default:"nothing"}}
length
返回值的長度。它對字符串和列表都起作用。例如:
{{ value|length }}
如果 value 是 [‘a(chǎn)’, ‘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
如果字符串字符多于指定的字符數(shù)量,那么會被截斷。截斷的字符串將以可翻譯的省略號序列(“…”)結(jié)尾。
參數(shù):要截斷的字符數(shù)
例如:
{{ value|truncatechars:9}}
safe
Django的模板中會對HTML標簽和JS等語法標簽進行自動轉(zhuǎn)義,原因顯而易見,這樣是為了安全。但是有的時候我們可能不希望這些HTML元素被轉(zhuǎn)義,比如我們做一個內(nèi)容管理系統(tǒng),后臺添加的文章中是經(jīng)過修飾的,這些修飾可能是通過一個類似于FCKeditor編輯加注了HTML修飾符的文本,如果自動轉(zhuǎn)義的話顯示的就是保護HTML標簽的源文件。為了在Django中關(guān)閉HTML的自動轉(zhuǎn)義有兩種方式,如果是一個單獨的變量我們可以通過過濾器“|safe”的方式告訴Django這段代碼是安全的不必轉(zhuǎn)義。比如:
value="<a href="">點擊</a>"
{{ value|safe}}from django.utils.safestring import mark_safe
res = mark_safe('<h1>HELLO WORLD</h1>')
其它過濾器(了解)
過濾器 | 描述 | 示例 |
upper | 以大寫方式輸出 | |
add | 給value加上一個數(shù)值 | |
addslashes | 單引號加上轉(zhuǎn)義號 | |
capfirst | 第一個字母大寫 | |
center | 輸出指定長度的字符串,把變量居中 | |
cut | 刪除指定字符串 | |
date | 格式化日期 | |
default | 如果值不存在,則使用默認值代替 | |
default_if_none | 如果值為None, 則使用默認值代替 | |
dictsort | 按某字段排序,變量必須是一個dictionary | |
dictsortreversed | 按某字段倒序排序,變量必須是dictionary | |
divisibleby | 判斷是否可以被數(shù)字整除 | |
escape | 按HTML轉(zhuǎn)義,比如將”<”轉(zhuǎn)換為”<” | |
filesizeformat | 增加數(shù)字的可讀性,轉(zhuǎn)換結(jié)果為13KB,89MB,3Bytes等 | |
first | 返回列表的第1個元素,變量必須是一個列表 | |
floatformat | 轉(zhuǎn)換為指定精度的小數(shù),默認保留1位小數(shù) | |
get_digit | 從個位數(shù)開始截取指定位置的數(shù)字 | |
join | 用指定分隔符連接列表 | |
length | 返回列表中元素的個數(shù)或字符串長度 | |
length_is | 檢查列表,字符串長度是否符合指定的值 | |
linebreaks | 用 或 | |
linebreaksbr | 用 | |
linenumbers | 為變量中的每一行加上行號 | |
ljust | 輸出指定長度的字符串,變量左對齊 | |
lower | 字符串變小寫 | |
make_list | 將字符串轉(zhuǎn)換為列表 | |
pluralize | 根據(jù)數(shù)字確定是否輸出英文復數(shù)符號 | |
random | 返回列表的隨機一項 | |
removetags | 刪除字符串中指定的HTML標記 | |
rjust | 輸出指定長度的字符串,變量右對齊 | |
slice | 切片操作, 返回列表 | |
slugify | 在字符串中留下減號和下劃線,其它符號刪除,空格用減號替換 | |
stringformat | 字符串格式化,語法同python | |
time | 返回日期的時間部分 | |
timesince | 以“到現(xiàn)在為止過了多長時間”顯示時間變量 | |
timeuntil | 以“從現(xiàn)在開始到時間變量”還有多長時間顯示時間變量 | |
title | 每個單詞首字母大寫 | |
truncatewords | 將字符串轉(zhuǎn)換為省略表達方式 | |
truncatewords_html | 同上,但保留其中的HTML標簽 | |
urlencode | 將字符串中的特殊字符轉(zhuǎn)換為url兼容表達方式 | |
urlize | 將變量字符串中的url由純文本變?yōu)殒溄?/p> | |
wordcount | 返回變量字符串中的單詞數(shù) |
?模版之標簽
標簽看起來像是這樣的: {% tag %}
標簽比變量更加復雜:一些在輸出中創(chuàng)建文本,一些通過循環(huán)或邏輯來控制流程,一些加載其后的變量將使用到的額外信息到模版中。
一些標簽需要開始和結(jié)束標簽 (例如{% tag %} ...標簽 內(nèi)容 ... {% endtag %})
for標簽
遍歷每一個元素:
{% for person in person_list %}<p>{{ person.name }}</p>
{% endfor %}#可以利用{% for obj in list reversed %}反向完成循環(huán)。
遍歷一個字典:
{% for key,val in dic.items %}<p>{{ key }}:{{ val }}</p>
{% endfor %}{% for foo in d.keys %}<p>{{ foo }}</p>
{% endfor %}{% for foo in d.values %}<p>{{ foo }}</p>
{% endfor %}{% for foo in d.items %}<p>{{ foo }}</p>
{% endfor %}
注:循環(huán)序號可以通過{{forloop}}顯示
forloop.counter The current iteration of the loop (1-indexed) 當前循環(huán)的索引值(從1開始)
forloop.counter0 The current iteration of the loop (0-indexed) 當前循環(huán)的索引值(從0開始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 當前循環(huán)的倒序索引值(從1開始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 當前循環(huán)的倒序索引值(從0開始)
forloop.first True if this is the first time through the loop 當前循環(huán)是不是第一次循環(huán)(布爾值)
forloop.last True if this is the last time through the loop 當前循環(huán)是不是最后一次循環(huán)(布爾值)
forloop.parentloop 本層循環(huán)的外層循環(huán)
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值),對應的內(nèi)容塊會輸出。{% if num > 100 or num < 0 %}<p>無效</p>
{% elif num > 80 and num < 100 %}<p>優(yōu)秀</p>
{% else %}<p>湊活吧</p>
{% endif %}if語句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。
with
使用一個簡單地名字緩存一個復雜的變量,當你需要使用一個“昂貴的”方法(比如訪問數(shù)據(jù)庫)很多次的時候是非常有用的
例如:
d = {'username':'kevin','age':18,'info':'這個人有點意思','hobby':[111,222,333,{'info':'NB'}]}# with起別名
{% with d.hobby.3.info as nb %}<p>{{ nb }}</p>在with語法內(nèi)就可以通過as后面的別名快速的使用到前面非常復雜獲取數(shù)據(jù)的方式<p>{{ d.hobby.3.info }}</p>
{% endwith %}{% with total=business.employees.count %}{{ total }} employee{{ total|pluralize }}
{% endwith %}
不要寫成as
csrf_token
{% csrf_token%}
這個標簽用于跨站請求偽造保護
?模版導入和繼承
模版導入
語法:{% include '模版名稱' %}如:{% include 'adv.html' %}
?基本代碼示例
<div class="adv"><div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Panel title</h3></div><div class="panel-body">Panel content</div></div><div class="panel panel-danger"><div class="panel-heading"><h3 class="panel-title">Panel title</h3></div><div class="panel-body">Panel content</div></div><div class="panel panel-warning"><div class="panel-heading"><h3 class="panel-title">Panel title</h3></div><div class="panel-body">Panel content</div></div> </div>
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">{# <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">#}<style>* {margin: 0;padding: 0;}.header {height: 50px;width: 100%;background-color: #369;}</style> </head> <body> <div class="header"></div><div class="container"><div class="row"><div class="col-md-3">{% include 'adv.html' %}</div><div class="col-md-9">{% block conn %}<h1>你好</h1>{% endblock %}</div></div></div></body> </html>
{% extends 'base.html' %}{% block conn %}{{ block.super }} 是啊{% endblock conn%}
?模版繼承
Django模版引擎中最強大也是最復雜的部分就是模版繼承了。模版繼承可以讓您創(chuàng)建一個基本的“骨架”模版,它包含您站點中的全部元素,并且可以定義能夠被子模版覆蓋的 blocks 。
通過從下面這個例子開始,可以容易的理解模版繼承:
<!DOCTYPE html> <html lang="en"> <head><link rel="stylesheet" href="style.css"/><title>{% block title %}My amazing site{% endblock %}</title> </head><body> <div id="sidebar">{% block sidebar %}<ul><li><a href="/">Home</a></li><li><a href="/blog/">Blog</a></li></ul>{% endblock %} </div><div id="content">{% block content %}{% endblock %} </div> </body> </html>
這個模版,我們把它叫作 base.html, 它定義了一個可以用于兩列排版頁面的簡單HTML骨架?!白幽0妗钡墓ぷ魇怯盟鼈兊膬?nèi)容填充空的blocks。
在這個例子中, block 標簽定義了三個可以被子模版內(nèi)容填充的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 標簽是這里的關(guān)鍵。它告訴模版引擎,這個模版“繼承”了另一個模版。當模版系統(tǒng)處理這個模版時,首先,它將定位父模版——在此例中,就是“base.html”。
那時,模版引擎將注意到 base.html 中的三個 block 標簽,并用子模版中的內(nèi)容來替換這些block。根據(jù) blog_entries 的值,輸出可能看起來是這樣的:<!DOCTYPE html> <html lang="en"> <head><link rel="stylesheet" href="style.css" /><title>My amazing blog</title> </head><body><div id="sidebar"><ul><li><a href="/">Home</a></li><li><a href="/blog/">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,所以系統(tǒng)使用了父模版中的值。父模版的 `{% block %}` 標簽中的內(nèi)容總是被用作備選內(nèi)容(fallback)。
這種方式使代碼得到最大程度的復用,并且使得添加內(nèi)容到共享的內(nèi)容區(qū)域更加簡單,例如,部分范圍內(nèi)的導航。
**這里是使用繼承的一些提示**:
如果你在模版中使用 `{% extends %}` 標簽,它必須是模版中的第一個標簽。其他的任何情況下,模版繼承都將無法工作。
在base模版中設(shè)置越多的 `{% block %}` 標簽越好。請記住,子模版不必定義全部父模版中的blocks,所以,你可以在大多數(shù)blocks中填充合理的默認內(nèi)容,然后,只定義你需要的那一個。多一點鉤子總比少一點好。
如果你發(fā)現(xiàn)你自己在大量的模版中復制內(nèi)容,那可能意味著你應該把內(nèi)容移動到父模版中的一個 `{% block %}` 中。
If you need to get the content of the block from the parent template, the `{{ block.super }}` 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 `{{ block.super }}` 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 %}` 標簽被關(guān)閉了。
不能在一個模版中定義多個相同名字的 `block` 標簽。
實戰(zhàn)代碼實例
在Bootstrap中文網(wǎng)獲取模塊
?
、
導航條
巨幕
縮略圖
views.py模塊
def home(request):return render(request,'home.html')def login(request):return render(request,'login.html')def register(request):return render(request,'register.html')
?urls.py模塊
from django.conf.urls import url from django.contrib import admin from app01 import viewsurlpatterns = [url(r'^admin/', admin.site.urls),url(r'^index/',views.index),url(r'^home/',views.home),url(r'^login/',views.login),url(r'^register/',views.register),]
templates\home.html模塊
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>{% block css %}{% endblock %}</head> <body> <nav class="navbar navbar-default"><div class="container-fluid"><!-- Brand and toggle get grouped for better mobile display --><div class="navbar-header"><button type="button" class="navbar-toggle collapsed" data-toggle="collapse"data-target="#bs-example-navbar-collapse-1" aria-expanded="false"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a class="navbar-brand" href="#">《遮天》</a></div><!-- Collect the nav links, forms, and other content for toggling --><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><ul class="nav navbar-nav"><li class="active"><a href="#">荒古圣體<span class="sr-only">(current)</span></a></li><li><a href="#">極盡升華</a></li><li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"aria-expanded="false">極道帝兵<span class="caret"></span></a><ul class="dropdown-menu"><li><a href="#">荒塔</a></li><li><a href="#">仙鐘</a></li><li><a href="#">吞天魔罐</a></li><li role="separator" class="divider"></li><li><a href="#">青蓮帝兵</a></li><li role="separator" class="divider"></li><li><a href="#">仙鐵棍</a></li></ul></li></ul><form class="navbar-form navbar-left"><div class="form-group"><input type="text" class="form-control" placeholder="Search"></div><button type="submit" class="btn btn-default">Submit</button></form><ul class="nav navbar-nav navbar-right"><li><a href="#">Link</a></li><li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"aria-expanded="false">Dropdown <span class="caret"></span></a><ul class="dropdown-menu"><li><a href="#">Action</a></li><li><a href="#">Another action</a></li><li><a href="#">Something else here</a></li><li role="separator" class="divider"></li><li><a href="#">Separated link</a></li></ul></li></ul></div><!-- /.navbar-collapse --></div><!-- /.container-fluid --> </nav><div class="container-fluid"><div class="row"><div class="col-md-3"><div class="list-group">{% block ft %}<div class="list-group"><a href="/home/" class="list-group-item active">歡迎來到仙俠世界</a><a href="/login/" class="list-group-item">登陸星空古路</a><a href="/register/" class="list-group-item">加入圣地考核</a><a href="#" class="list-group-item">修仙技術(shù)支持</a><a href="#" class="list-group-item">更多</a></div>{% endblock %}</div></div><div class="col-md-9"><div class="panel panel-info"><div class="panel-heading">九秘</div>{% block content %}<div class="panel-body"><div class="jumbotron"><h1>少年,你想變強嗎</h1><p>加入我們</p><p><a class="btn btn-primary btn-lg" href="#" role="button">快來,快來</a></p></div><div class="row"><div class="col-sm-6 col-md-4"><div class="thumbnail"><img src="https://img1.baidu.com/it/u=803199455,778449086&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=1080"alt="..."><div class="caption"><h3>Thumbnail label</h3><p>...</p><p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"class="btn btn-default"role="button">Button</a></p></div></div></div><div class="col-sm-6 col-md-4"><div class="thumbnail"><img src="https://img1.baidu.com/it/u=3707885883,1615845000&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=337"alt="..."><div class="caption"><h3>Thumbnail label</h3><p>...</p><p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"class="btn btn-default"role="button">Button</a></p></div></div></div><div class="col-sm-6 col-md-4"><div class="thumbnail"><img src="https://img1.baidu.com/it/u=1395000385,3610786620&fm=253&fmt=auto&app=120&f=JPEG?w=889&h=500"alt="..."><div class="caption"><h3>Thumbnail label</h3><p>...</p><p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"class="btn btn-default"role="button">Button</a></p></div></div></div></div></div>{% endblock %}</div></div></div> </div> {% block js %}{% endblock %}</body> </html>
?login.html模塊
{% extends 'home.html' %}{% block css %}<style>h1{color:red;}</style> {% endblock %}{% block ft %}<div class="list-group"><a href="/home/" class="list-group-item active">歡迎來到仙俠世界</a><a href="/login/" class="list-group-item">登陸星空古路</a><a href="/register/" class="list-group-item">加入圣地考核</a></div> {% endblock %}{% block content %}<h1 class="text-center">登陸頁面</h1><div class="row"><div class="col-md-8 col-md-offset-2"><form action=""><div class="form-group">用戶名:<input type="text" class="form-control"></div><div class="form-group">密碼:<input type="text" class="form-control"></div><div class="form-group"><input type="submit" class="btn btn-success btn-block" value="提交"></div></form>{% include 'hahah.html' %}</div></div> {% endblock %}{% block js %}<script>alert('login')</script> {% endblock %}
register.html 模塊
{% extends 'home.html' %} {% block ft %}<div class="list-group"><a href="/home/" class="list-group-item active">歡迎來到仙俠世界</a><a href="/login/" class="list-group-item">登陸星空古路</a><a href="/register/" class="list-group-item">加入圣地考核</a></div> {% endblock %}{% block content %}<h1 class="text-center">注冊頁面</h1><div class="row"><div class="col-md-8 col-md-offset-2"><form action=""><div class="form-group">用戶名:<input type="text" class="form-control"></div><div class="form-group">密碼:<input type="text" class="form-control"></div><div class="form-group"><input type="submit" class="btn btn-success btn-block" value="提交"></div></form></div></div> {% endblock %}{% block js %}<script>alert('register')</script> {% endblock %}
END