开发者

@register.filter in my code

from django import template

register = template.Library()

class_converter = {
    "textinput":"textinput textInput",
    "fileinput":"fileinput fileUpload"
}

@register.filter#<--------
def is_checkbox(field):
    return field.field.widget.__class__.__name__.lower() == "checkboxinput"

@register.filter#<--------
def with_class(field):
    class_name = field.field.widget.__class__.__name__.lower()
    class_name = class_converter.get(class_name, class_name)
    if "class" in field.field.widget.attrs:
        field.field.widget.attrs['class'] += " %s" % class_name
    else:
        field.field.widget.attrs['class'] = class_name
    return unicode(field)

and register.filter function is:

def filter(self, name=None, filter_func=None):
        if name == None and filter_func == None:
 开发者_StackOverflow           # @register.filter()
            return self.filter_function
        elif filter_func == None:
            if(callable(name)):
                # @register.filter
                return self.filter_function(name)
            else:
                # @register.filter('somename') or @register.filter(name='somename')
                def dec(func):
                    return self.filter(name, func)
                return dec
        elif name != None and filter_func != None:
            # register.filter('somename', somefunc)
            self.filters[name] = filter_func
            return filter_func
        else:
            raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func))

so

@register.filter
def a():
    pass

is Equal

register.filter(name=None,filter_func=a)

yes??


Not exactly. The decorator syntax:

@register.filter
def a():
   pass

is syntactic sugar for:

def a():
    pass
a = register.filter(a)

So register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage however and returns the right thing even if the filter is sent as the first argument (see the if callable(name) branch)

It's more common to make decorators that can take multiple arguments do so with the function to be decorated being the first positional argument (or alternately being function factories/closures), but I have a feeling the reason django did it this way was for backwards-compatibility. Actually I vaguely remember it not being a decorator in the past, and then becoming a decorator in a later django version.


No. Simple decorators take the function they decorate as a parameter, and return a new function.

a = register.filter(a)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜