1. 程式人生 > 實用技巧 >Django基礎08篇 filter&tag

Django基礎08篇 filter&tag

1.Django自帶的過濾器filter

views.py中程式碼

def template_tags(request):
    import datetime
    content = '金三胖content金三胖contentSBcontentsbcontentcontentcontentcontentcontent'
    title = 'tiTLe'
    stus = ['xiaohei', 'xiaobai', 'lhy']
    info = {"money":9999}
    cur_date = datetime.datetime.now()
    name 
= '小白' age = 35 return render(request, 'template_tags.html', locals())

前端程式碼

{% load my_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板標籤</title>
</head>
<body>
    {#    Django自帶#}
    {#    擷取字串#}
    
<p>{{ content| truncatechars:30 }}</p> {# 大寫#} <p>{{ title|upper }}</p> {# 小寫#} <p>{{ title|lower }}</p> {# 獲取陣列長度#} <p>{{ stus|length}}</p> {# 切片#} <p>{{ stus|slice:"0:4"}}</p> {# 下標取值#} <
p>{{ stus.0 }}</p> {# 拼接字串#} <p>{{ stus|join:'-' }}</p> {# 字典取值#} <p>{{ info.money }}</p> {# 字串後新增#} <p>{{ name|add:",你好" }}</p> {# 整數加#} <p>{{ age|add:1 }}</p> {# 格式化時間#} <p>{{ cur_date | date:"Y-m-d H:i:s" }}</p> {% with class="天馬座" %} <p>{{ class }}</p> {% endwith %} </body> </html>
template_tags.html

頁面效果

2.Django自定義過濾器filter

1).在子專案(此處在user目錄下)的根目錄下建立templatetags目錄

2).建立my_tags.py檔案

3).固定匯入

  fromdjangoimporttemplate

 register=template.Library()# register變數必須這麼定義 4).使用裝飾器@register.filter修飾自定義的filter方法
from django.template import Library

register = Library()
@register.filter
def mingan(content):
    return content.replace("三胖", '小白')

@register.filter
def mingan2(content, s):
    return content.replace("三胖", s)

@register.simple_tag
def mingan3(content, *agrs):  # 支援多個引數
    for arg in agrs:
        content = content.replace(arg, '小白')
    return content

5). 在html檔案中匯入{%load tmpTags%}

6). 使用

{{ content| mingan }}    
此函式只有1個引數,管道符|左側的就是第一個引數傳給管道符後的函式
{{ content| mingan2:'大傻子' }}
此函式只有2個引數,管道符|左側的就是第一個引數傳給管道符後的函式,:後是第二個引數
{% mingan3 content 'sb' 'SB' '三胖' %}
此函式支援多個引數
{% load my_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板標籤</title>
</head>
<body>
    {#    自定義函式#}
    <p>{{ content| mingan }}</p>
    {#    自定義函式#}
    <p>{{ content| mingan2:'大傻子' }}</p>
    {% mingan3 content 'sb' 'SB' '三胖' %}
</body>
</html>
template_tags.html

效果如下: