手機(jī)網(wǎng)站制作與建設(shè)百度收錄網(wǎng)址提交
模板之變量
所有的數(shù)據(jù)類型都可以在模板中使用
render(request, 'index.html', context={''})
render(request, 'index.html', context=locals())
"""在模板中使用變量的時(shí)候,用的是字典的key值,key值value值一般保持一致"""詳細(xì)請(qǐng)看上一篇末尾
模版之過(guò)濾器
語(yǔ)法
{{obj|filter__name:param}} 變量名字|過(guò)濾器名稱:變量
類似于函數(shù),函數(shù)才可以傳遞參數(shù)
語(yǔ)法:
?? ?{{ obj|過(guò)濾器:參數(shù) }}
過(guò)濾器:
????default
? ? length
? ? filesizeformat
? ? date
? ? trancatechars
? ? slice
? ? safe
? ? mark_safe # 導(dǎo)入
default
如果一個(gè)變量是false或者為空,使用給定的默認(rèn)值。否則,使用變量的值。例如:
{{ value|default:"nothing"}}
length
返回值的長(zhǎng)度。它對(duì)字符串和列表都起作用。例如:
{{ value|length }}
如果 value 是 [‘a(chǎn)’, ‘b’, ‘c’, ‘d’],那么輸出是 4。
filesizeformat
將值格式化為一個(gè) “人類可讀的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)。例如:
{{ value|filesizeformat }}
如果 value 是 123456789,輸出將會(huì)是 117.7 MB。
date
如果 value=datetime.datetime.now()
{{ value|date:"Y-m-d"}}
slice
如果 value=”hello world”
{{ value|slice:"2:-1"}}
truncatechars
如果字符串字符多于指定的字符數(shù)量,那么會(huì)被截?cái)?。截?cái)嗟淖址畬⒁钥煞g的省略號(hào)序列(“…”)結(jié)尾。
參數(shù):要截?cái)嗟淖址麛?shù)
例如:
{{ value|truncatechars:9}}
safe
Django的模板中會(huì)對(duì)HTML標(biāo)簽和JS等語(yǔ)法標(biāo)簽進(jìn)行自動(dòng)轉(zhuǎn)義,原因顯而易見(jiàn),這樣是為了安全。但是有的時(shí)候我們可能不希望這些HTML元素被轉(zhuǎn)義,比如我們做一個(gè)內(nèi)容管理系統(tǒng),后臺(tái)添加的文章中是經(jīng)過(guò)修飾的,這些修飾可能是通過(guò)一個(gè)類似于FCKeditor編輯加注了HTML修飾符的文本,如果自動(dòng)轉(zhuǎn)義的話顯示的就是保護(hù)HTML標(biāo)簽的源文件。為了在Django中關(guān)閉HTML的自動(dòng)轉(zhuǎn)義有兩種方式,如果是一個(gè)單獨(dú)的變量我們可以通過(guò)過(guò)濾器“|safe”的方式告訴Django這段代碼是安全的不必轉(zhuǎn)義。比如:
value="<a href="">點(diǎn)擊</a>"
{{ value|safe}}from django.utils.safestring import mark_safe
res = mark_safe('<h1>HELLO WORLD</h1>')
其它過(guò)濾器(了解)
過(guò)濾器 | 描述 | 示例 |
upper | 以大寫(xiě)方式輸出 | |
add | 給value加上一個(gè)數(shù)值 | |
addslashes | 單引號(hào)加上轉(zhuǎn)義號(hào) | |
capfirst | 第一個(gè)字母大寫(xiě) | |
center | 輸出指定長(zhǎng)度的字符串,把變量居中 | |
cut | 刪除指定字符串 | |
date | 格式化日期 | |
default | 如果值不存在,則使用默認(rèn)值代替 | |
default_if_none | 如果值為None, 則使用默認(rèn)值代替 | |
dictsort | 按某字段排序,變量必須是一個(gè)dictionary | |
dictsortreversed | 按某字段倒序排序,變量必須是dictionary | |
divisibleby | 判斷是否可以被數(shù)字整除 | |
escape | 按HTML轉(zhuǎn)義,比如將”<”轉(zhuǎn)換為”<” | |
filesizeformat | 增加數(shù)字的可讀性,轉(zhuǎn)換結(jié)果為13KB,89MB,3Bytes等 | |
first | 返回列表的第1個(gè)元素,變量必須是一個(gè)列表 | |
floatformat | 轉(zhuǎn)換為指定精度的小數(shù),默認(rèn)保留1位小數(shù) | |
get_digit | 從個(gè)位數(shù)開(kāi)始截取指定位置的數(shù)字 | |
join | 用指定分隔符連接列表 | |
length | 返回列表中元素的個(gè)數(shù)或字符串長(zhǎng)度 | |
length_is | 檢查列表,字符串長(zhǎng)度是否符合指定的值 | |
linebreaks | 用 或 | |
linebreaksbr | 用 | |
linenumbers | 為變量中的每一行加上行號(hào) | |
ljust | 輸出指定長(zhǎng)度的字符串,變量左對(duì)齊 | |
lower | 字符串變小寫(xiě) | |
make_list | 將字符串轉(zhuǎn)換為列表 | |
pluralize | 根據(jù)數(shù)字確定是否輸出英文復(fù)數(shù)符號(hào) | |
random | 返回列表的隨機(jī)一項(xiàng) | |
removetags | 刪除字符串中指定的HTML標(biāo)記 | |
rjust | 輸出指定長(zhǎng)度的字符串,變量右對(duì)齊 | |
slice | 切片操作, 返回列表 | |
slugify | 在字符串中留下減號(hào)和下劃線,其它符號(hào)刪除,空格用減號(hào)替換 | |
stringformat | 字符串格式化,語(yǔ)法同python | |
time | 返回日期的時(shí)間部分 | |
timesince | 以“到現(xiàn)在為止過(guò)了多長(zhǎng)時(shí)間”顯示時(shí)間變量 | |
timeuntil | 以“從現(xiàn)在開(kāi)始到時(shí)間變量”還有多長(zhǎng)時(shí)間顯示時(shí)間變量 | |
title | 每個(gè)單詞首字母大寫(xiě) | |
truncatewords | 將字符串轉(zhuǎn)換為省略表達(dá)方式 | |
truncatewords_html | 同上,但保留其中的HTML標(biāo)簽 | |
urlencode | 將字符串中的特殊字符轉(zhuǎn)換為url兼容表達(dá)方式 | |
urlize | 將變量字符串中的url由純文本變?yōu)殒溄?/p> | |
wordcount | 返回變量字符串中的單詞數(shù) |
?模版之標(biāo)簽
標(biāo)簽看起來(lái)像是這樣的: {% tag %}
標(biāo)簽比變量更加復(fù)雜:一些在輸出中創(chuàng)建文本,一些通過(guò)循環(huán)或邏輯來(lái)控制流程,一些加載其后的變量將使用到的額外信息到模版中。
一些標(biāo)簽需要開(kāi)始和結(jié)束標(biāo)簽 (例如{% tag %} ...標(biāo)簽 內(nèi)容 ... {% endtag %})
for標(biāo)簽
遍歷每一個(gè)元素:
{% for person in person_list %}<p>{{ person.name }}</p>
{% endfor %}#可以利用{% for obj in list reversed %}反向完成循環(huán)。
遍歷一個(gè)字典:
{% 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)序號(hào)可以通過(guò){{forloop}}顯示
forloop.counter The current iteration of the loop (1-indexed) 當(dāng)前循環(huán)的索引值(從1開(kāi)始)
forloop.counter0 The current iteration of the loop (0-indexed) 當(dāng)前循環(huán)的索引值(從0開(kāi)始)
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 當(dāng)前循環(huán)的倒序索引值(從1開(kāi)始)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 當(dāng)前循環(huán)的倒序索引值(從0開(kāi)始)
forloop.first True if this is the first time through the loop 當(dāng)前循環(huán)是不是第一次循環(huán)(布爾值)
forloop.last True if this is the last time through the loop 當(dāng)前循環(huán)是不是最后一次循環(huán)(布爾值)
forloop.parentloop 本層循環(huán)的外層循環(huán)
for … empty
# for 標(biāo)簽帶有一個(gè)可選的{% empty %} 從句,以便在給出的組是空的或者沒(méi)有被找到時(shí),可以有所操作。
{% for person in person_list %}<p>{{ person.name }}</p>{% empty %}<p>sorry,no person here</p>
{% endfor %}
if 標(biāo)簽
# {% if %}會(huì)對(duì)一個(gè)變量求值,如果它的值是True(存在、不為空、且不是boolean類型的false值),對(duì)應(yīng)的內(nèi)容塊會(huì)輸出。{% if num > 100 or num < 0 %}<p>無(wú)效</p>
{% elif num > 80 and num < 100 %}<p>優(yōu)秀</p>
{% else %}<p>湊活吧</p>
{% endif %}if語(yǔ)句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判斷。
with
使用一個(gè)簡(jiǎn)單地名字緩存一個(gè)復(fù)雜的變量,當(dāng)你需要使用一個(gè)“昂貴的”方法(比如訪問(wèn)數(shù)據(jù)庫(kù))很多次的時(shí)候是非常有用的
例如:
d = {'username':'kevin','age':18,'info':'這個(gè)人有點(diǎn)意思','hobby':[111,222,333,{'info':'NB'}]}# with起別名
{% with d.hobby.3.info as nb %}<p>{{ nb }}</p>在with語(yǔ)法內(nèi)就可以通過(guò)as后面的別名快速的使用到前面非常復(fù)雜獲取數(shù)據(jù)的方式<p>{{ d.hobby.3.info }}</p>
{% endwith %}{% with total=business.employees.count %}{{ total }} employee{{ total|pluralize }}
{% endwith %}
不要寫(xiě)成as
csrf_token
{% csrf_token%}
這個(gè)標(biāo)簽用于跨站請(qǐng)求偽造保護(hù)
?模版導(dǎo)入和繼承
模版導(dǎo)入
語(yǔ)法:{% 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模版引擎中最強(qiáng)大也是最復(fù)雜的部分就是模版繼承了。模版繼承可以讓您創(chuàng)建一個(gè)基本的“骨架”模版,它包含您站點(diǎn)中的全部元素,并且可以定義能夠被子模版覆蓋的 blocks 。
通過(guò)從下面這個(gè)例子開(kāi)始,可以容易的理解模版繼承:
<!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>
這個(gè)模版,我們把它叫作 base.html, 它定義了一個(gè)可以用于兩列排版頁(yè)面的簡(jiǎn)單HTML骨架?!白幽0妗钡墓ぷ魇怯盟鼈兊膬?nèi)容填充空的blocks。
在這個(gè)例子中, block 標(biāo)簽定義了三個(gè)可以被子模版內(nèi)容填充的block。 block 告訴模版引擎: 子模版可能會(huì)覆蓋掉模版中的這些位置。
子模版可能看起來(lái)是這樣的:
{% 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 標(biāo)簽是這里的關(guān)鍵。它告訴模版引擎,這個(gè)模版“繼承”了另一個(gè)模版。當(dāng)模版系統(tǒng)處理這個(gè)模版時(shí),首先,它將定位父模版——在此例中,就是“base.html”。
那時(shí),模版引擎將注意到 base.html 中的三個(gè) block 標(biāo)簽,并用子模版中的內(nèi)容來(lái)替換這些block。根據(jù) blog_entries 的值,輸出可能看起來(lái)是這樣的:<!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>
請(qǐng)注意,子模版并沒(méi)有定義 `sidebar` block,所以系統(tǒng)使用了父模版中的值。父模版的 `{% block %}` 標(biāo)簽中的內(nèi)容總是被用作備選內(nèi)容(fallback)。
這種方式使代碼得到最大程度的復(fù)用,并且使得添加內(nèi)容到共享的內(nèi)容區(qū)域更加簡(jiǎn)單,例如,部分范圍內(nèi)的導(dǎo)航。
**這里是使用繼承的一些提示**:
如果你在模版中使用 `{% extends %}` 標(biāo)簽,它必須是模版中的第一個(gè)標(biāo)簽。其他的任何情況下,模版繼承都將無(wú)法工作。
在base模版中設(shè)置越多的 `{% block %}` 標(biāo)簽越好。請(qǐng)記住,子模版不必定義全部父模版中的blocks,所以,你可以在大多數(shù)blocks中填充合理的默認(rèn)內(nèi)容,然后,只定義你需要的那一個(gè)。多一點(diǎn)鉤子總比少一點(diǎn)好。
如果你發(fā)現(xiàn)你自己在大量的模版中復(fù)制內(nèi)容,那可能意味著你應(yīng)該把內(nèi)容移動(dòng)到父模版中的一個(gè) `{% 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 %}` 標(biāo)簽一個(gè) *名字* 。例如:
?{%block content %}...{%endblock content %}
?在大型模版中,這個(gè)方法幫你清楚的看到哪一個(gè) ?`{% block %}` 標(biāo)簽被關(guān)閉了。
不能在一個(gè)模版中定義多個(gè)相同名字的 `block` 標(biāo)簽。
實(shí)戰(zhàn)代碼實(shí)例
在Bootstrap中文網(wǎng)獲取模塊
?
、
導(dǎo)航條
巨幕
縮略圖
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">歡迎來(lái)到仙俠世界</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>少年,你想變強(qiáng)嗎</h1><p>加入我們</p><p><a class="btn btn-primary btn-lg" href="#" role="button">快來(lái),快來(lái)</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">歡迎來(lái)到仙俠世界</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">登陸頁(yè)面</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">歡迎來(lái)到仙俠世界</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">注冊(cè)頁(yè)面</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