Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo custom template filter tag trong Django


Django cho phép tự viết filter template để xử lý chuỗi, số... ngay trong template.

Các bước

  1. Tạo thư mục templatetags trong app, có file __init__.py.

  2. Tạo file filter, ví dụ upperfilter.py:

    from django.template import Library
    register = Library()
    @register.filter
    def upper(value):
        return value.upper()
  3. Trong template: {% load upperfilter %}{{ "hello" | upper }} → HELLO

Lưu ý

Cấu hình TEMPLATES['DIRS'] trỏ đến thư mục templates của app.