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

2024-01-07

 # -*- 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

模板.html

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

Error:

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

2. 你添加了标签吗?你需要类似的东西

{% load apptags %}

在你的模板中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 django 框架中正确制作自定义过滤器? 的相关文章

随机推荐