Django(part13)--过滤器
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Django(part13)--过滤器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                學習筆記,僅供參考,有錯必糾
文章目錄
- 模板
- 過濾器
- 常用的過濾器
- 舉個例子
 
- 轉義(escape)
- 自動轉義(autoscape)
- 舉個例子
 
 
 
模板
過濾器
- 作用
在變量輸出前對變量的值進行處理,我們可以通過使用過濾器來改變變量的顯示。
- 語法
常用的過濾器
| default | 如果value的計算結果為False,則使用給定的默認值,否則,使用該value | 
| default_if_none | 如果(且僅當) value為None,則使用給定的默認值否則,使用該value | 
| floatformat | 當不使用參數時,將浮點數舍入到小數點后一位,但前提是要顯示小數部分。 | 
| truncatechars | 如果字符串字符多于指定的字符數量,那么會被截斷。 截斷的字符串將以可翻譯的省略號序列("…")結尾。 | 
| truncatewords | 在一定數量的字后截斷字符串 | 
| lower | 將字符串全部轉換為小寫 | 
| upper | 將字符串全部轉換為大寫 | 
舉個例子
page7.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>過濾器</title> </head> <body><h1>string={{ string }}</h1><h1>大寫內容是:{{ string | upper }}</h1><h1>省略后的內容是:{{ string | truncatechars:11 }}</h1><h1>{{ string | truncatechars:11 | upper }}</h1><h2>{{a|add:2}}和{{b|add:3}}</h2> </body> </html>views.py
def page7_template(request):string = "Welcome to Anhui University of Finance and Economics"a = 100b = 200return render(request, "page7.html", locals())locals方法會返回局部變量的字典,在本例中locals方法會返回{“string”:“Welcome to Anhui University of Finance and Economics”,“a”:100,“b”:200}
urls.py
urlpatterns = [path('admin/', admin.site.urls),re_path(r'page7_template/$', views.page7_template), ]向http://127.0.0.1:8000/page7_template/發起請求:
轉義(escape)
在這里,轉義就是把HTML語言的關鍵字過濾掉。例如,<a>為html的標簽,如果要在HTML頁面上呈現<a>,其源代碼就必須是<a>
- Django中對HTML關鍵字的替換
| < | < | 
| > | > | 
| '單引號 | ' | 
| "雙引號 | " | 
| & | & | 
自動轉義(autoscape)
語法:
{% autoescape on %} {{body}} {% endautoescape %}舉個例子
page7.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>過濾器</title> </head> <body><h1>string={{ string }}</h1><h1>大寫內容是:{{ string | upper }}</h1><h1>省略后的內容是:{{ string | truncatechars:11 }}</h1>{% autoescape on %}{{ a }}{% endautoescape %} </body> </html>views.py
def page7_template(request):string = "Welcome to Anhui University of Finance and Economics"a = "<span>Huang</span>"b = 200return render(request, "page7.html", locals())urls.py
urlpatterns = [path('admin/', admin.site.urls),re_path(r'page7_template/$', views.page7_template), ]向http://127.0.0.1:8000/page7_template/發起請求:
總結
以上是生活随笔為你收集整理的Django(part13)--过滤器的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 第三次学JAVA再学不好就吃翔(part
- 下一篇: Flash找你们制作漂亮的文字动画效果
