2011-02-08 55 views
3
# -*- 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如何在django框架中正确定制过滤器?

... 
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' 

这从文件的工作标签很好,但过滤不。但我不知道为什么......

回答

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 

2.您是否包含标签?您需要类似于

{% load apptags %} 

在您的模板。

+0

它做...而templatetags和“包括”。但没有解决我的问题,以及我如何编写自定义标签。 – kspacja 2011-02-08 21:58:10

+2

你不``包括``标签库,你`加载`它:`{%load apptags%}` – 2011-02-08 23:27:05

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