Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Custom Filter Tags เองใน Django


Filters ช่วยมาก มี built-in filters หลายตัวใน Django เราสามารถสร้าง Custom Filters เองได้ ใช้ใน template ไฟล์ได้ทุกที่ เช่น แปลงตัวพิมพ์เล็กเป็นใหญ่ใน HTML

บทความนี้สอนสร้าง Custom Template Filter Tag ใน Django

ตัวอย่าง

สร้างโปรเจกต์และแอป

เพิ่มโฟลเดอร์ templates และ templatetags ในรูทของแอป โครงสร้างโปรเจกต์:

การสร้าง Custom Filter Tags เองใน Django

ตรวจสอบตัวแปร TEMPLATES ใน settings.py:

import os
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'example/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

เพิ่ม "example" ใน INSTALLED_APPS

ใน templates เพิ่ม home.html ว่างไว้ก่อน

ใน views.py ของ example:

from django.shortcuts import render
def main(request):
    return render(request, "home.html")

ใน urls.py ของโปรเจกต์:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('', include('example.urls')),
    path('admin/', admin.site.urls),
]

ใน urls.py ของแอป example:

from django.urls import path, include
from . import views
urlpatterns = [
    path('', views.main, name="main")
]

สร้าง __init__.py ใน templatetags และไฟล์ฟิลเตอร์ upperfilter.py:

from django.template import Library
register = Library()

@register.filter
def upper(value):
    return value.upper()

นำเข้า Library ลงทะเบียน สร้างฟังก์ชัน/ฟิลเตอร์ชื่อ upper ลงทะเบียนด้วย decorator

กลับไป home.html เพิ่ม:

<!DOCTYPE html> <html>
<head> <title>Tut</title> </head>
<body>
    {% load upperfilter %}
    <h1>{{ "hi friends how are you" | upper }}</h1>
</body> </html>

โหลดฟิลเตอร์และใช้ใน <h1> แปลงพิมพ์เล็กเป็นพิมพ์ใหญ่

เอาต์พุต

ไม่ใช้ฟิลเตอร์ – การสร้าง Custom Filter Tags เองใน Django

ใช้ฟิลเตอร์ – การสร้าง Custom Filter Tags เองใน Django