如何在django框架中正确制作自定义过滤器?

ksp*_*cja 3 python django django-template-filters

 # -*- 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
Run Code Online (Sandbox Code Playgroud)

template.html

...
initGeolocation2({{ place.longitude|commatodot }}, {{ place.latitude|commatodot }}, "MAIN");
...
Run Code Online (Sandbox Code Playgroud)

错误:

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'
Run Code Online (Sandbox Code Playgroud)

来自文件的这个标签运行良好,但过滤器没有.但我不知道为什么......

mip*_*adi 24

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
Run Code Online (Sandbox Code Playgroud)

你有标签吗?你需要类似的东西

{% load apptags %}
Run Code Online (Sandbox Code Playgroud)

在你的模板中.

  • 你没有"包含"一个标记库,你"加载"它:`{%load apptags%}` (2认同)

Grv*_*agi 9

要在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/点击此链接