簡體   English   中英

如何在我的 django 項目中創建自定義模板標簽

[英]How to create a custom templatetag in my django project

我一直在嘗試在我的項目中創建自定義模板標簽,但它不起作用

這是我的結構化項目:

我在我的索引目錄中創建了一個文件夾,名為 templatetags > __init__.py , extras.py ,在 extras 文件中:

from django import template
register = template.Library()
def cut(value):
   return value.replace("no", 'yes')

模板:{% 加載 poll_extras %}

但我得到了這個

錯誤

我在我的索引目錄中創建了一個文件夾,名為templatetags > __init__.py , extras.py ,在 extras 文件中。

您應該將其添加到應用程序中。 因此,在根目錄中,您有應用程序的目錄,並在該應用程序目錄下創建一個templatetags目錄。

  # ← name of the app
    templatetags/
        __init__.py
        extra.py

這個應用程序應該是一個已安裝的應用程序,所以你在INSTALLED_APPS設置 [Django-doc] 中添加應用程序的名稱:

# settings.py

INSTALLED_APP = [
    # …,
    '',
    # …,
]

您還需要注冊模板標簽:

# /templatetags/extra.py

from django import template
register = template.Library()

@register.tag  # ← register the template tag
def cut(value):
   return value.replace("no", 'yes')

如果要注冊模板過濾器,而不是模板標記,則應使用@register.filter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM