#暑期創作大賽#
使用模闆過濾器指令
建立一個 Django 項目,并在 views.py 中定義一個視圖函數,将資料傳遞給模闆:
# views.py
from django.shortcuts import render
def my_view(request):
my_date = datetime.date(2022, 1, 1)
my_time = datetime.time(13, 30, 45)
my_text = "This is a long text that needs to be truncated."
my_list = [1, 2, 3, 4, 5]
return render(request, 'my_template.html', {
'my_date': my_date,
'my_time': my_time,
'my_text': my_text,
'my_list': my_list
})
在 my_template.html 模闆中使用模闆過濾器指令處理資料:
<!-- my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Template</title>
</head>
<body>
<h1>Date: {{ my_date | date:"F j, Y" }}</h1>
<p>Time: {{ my_time | time:"H:i:s" }}</p>
<p>Truncated Text: {{ my_text | truncatechars:30 }}</p>
<p>Text with Line Breaks: {{ my_text | linebreaks }}</p>
<p>List Length: {{ my_list | length }}</p>
</body>
</html>
在 urls.py 中配置 URL 路由,将視圖函數與 URL 關聯起來:
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('my-view/', views.my_view, name='my_view'),
]
現在,當你通路 http://localhost:8000/my-view/ 時,将會渲染 my_template.html 模闆,并在頁面上顯示經過模闆過濾器指令處理後的資料:
- Date: January 1, 2022
- Time: 13:30:45
- Truncated Text: This is a long text that need...
- Text with Line Breaks:
This is a long text.
It has two lines.
- List Length: 5
這個案例展示了如何在 Django 模闆中使用模闆過濾器指令來處理資料,以便在頁面上展示格式化的日期、時間,截取和換行處理的文本,以及清單的長度等資訊。
自定義過濾器
在Django中,你可以通過自定義過濾器來拓展模闆語言的功能。下面是一個示例,展示如何自定義一個過濾器:
在你的Django項目中的任意一個app下建立一個名為templatetags的檔案夾(如果該檔案夾已經存在則跳過此步驟)。
在templatetags檔案夾下建立一個名為custom_filters.py的Python檔案。
在custom_filters.py中編寫你的自定義過濾器。例如,下面是一個将字元串轉換為大寫的過濾器的示例:
from django import template
register = template.Library()
@register.filter(name='uppercase')
def uppercase(value):
return value.upper()
在你的模闆中加載自定義過濾器。在你的模闆的頂部添加以下代碼:
{% load custom_filters %}
- 在模闆中使用自定義過濾器。例如,要将一個變量my_variable轉換為大寫,你可以這樣寫:
{{ my_variable|uppercase }}
這是一個簡單的示例,你可以根據自己的需求編寫更複雜的自定義過濾器。記得在完成以上步驟後重新啟動Django開發伺服器,以便讓自定義過濾器生效。