如何在django框架中正确使定制过滤器? [英] How to properly make custom filter in django framework?
本文介绍了如何在django框架中正确使定制过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
register = template.Library()
$ b $
b @ register.inclusion_tag('menu / create_minimenu.html',took_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);
...
错误:
$ /
无效过滤器:'commatodot'
请求方法:GET
请求URL:http:// localhost:8000 / places / 3 /
Django版本:1.2.4
异常类型:TemplateSyntaxError
异常值:
无效的过滤器: 'commatodot'
这个来自文件的标签工作得很好,但是过滤器没有。但我不知道为什么...
解决方案
1。您将应用程序中的过滤器文件放在 templatetags
模块中吗?即,您应该有一个结构:
项目/
my_app /
templatetags /
__init__.py#重要!它使模板成为一个模块。您可以将过滤器放在其中或另一个文件中。
apptags.py#或者将它们放在__init__.py
2。你是否包含标签?你需要像
{%load apptags%}
。
# -*- 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");
...
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'
This tags from file work well, but the filter not. But I don't know why...
解决方案
1. Did you put the file with the filters inside a templatetags
module in your app? I.e., you should have a structure like:
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. Did you include the tags? You need something like
{% load apptags %}
in your template.
这篇关于如何在django框架中正确使定制过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文