簡體   English   中英

如何在django框架中正確制作自定義過濾器?

[英]How to properly make custom filter in django framework?

 # -*- coding: utf-8 -*-
from django import template
register = template.Library()

@register.inclusion_tag('menu/create_minimenu.html', takes_context = True)
def minimenu(context):
....
....
@register.inclusion_tag('menu/create_topmenu.html', takes_context = True)
def topmenu(context):
....
....
@register.filter(name = 'commatodot')
def commatodot(value, arg):
    return str(value).replace(",", '.')
commatodot.isSafe = True

template.html

...
initGeolocation2({{ place.longitude|commatodot }}, {{ place.latitude|commatodot }}, "MAIN");
...

錯誤:

TemplateSyntaxError at /places/3/

Invalid filter: 'commatodot'

Request Method:     GET
Request URL:    http://localhost:8000/places/3/
Django Version:     1.2.4
Exception Type:     TemplateSyntaxError
Exception Value:    

Invalid filter: 'commatodot'

來自文件的這個標簽運行良好,但過濾器沒有。 但我不知道為什么......

1.您是否將帶有過濾器的文件放在應用程序的templatetags模塊中? 即,你應該有一個像這樣的結構:

project/
  my_app/
    templatetags/
      __init__.py    # Important! It makes templatetags a module. You can put your filters here, or in another file.
      apptags.py     # Or just put them in __init__.py

你有標簽嗎? 你需要類似的東西

{% load apptags %}

在你的模板中。

要在django中創建自定義過濾器,請按照下列步驟操作

1)。 在您的應用中創建template_tags文件夾

2)。 在此文件夾中添加/復制__init__.py文件,以確保這是一個python文件夾。

3)。 添加your_custom_filter_name.py文件如下所示:

from django import template register = template.Library()

@register.filter(name = 'get_class') '''A filter for get class name of object.''' def get_class(value): return value.__class__.__name__

4)。 要加載此過濾器,請在html模板中將{%load your_custom_filter_name%}添加到頂部。

5)。 重啟你的服務器 ,享受:)

有關更多信息, 請訪問https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/點擊此鏈接

暫無
暫無

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

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