Functional Filters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from django.template import Library
from functools import partial

register = Library()

@register.filter
def method(value, arg):
    """
    Prepare the specified object for invoking a method.

    This is used in conjunction with the "with" and "call" tags.  For
    example, with

      class Foo:
        def bar(self, a, b, c):
          return "a is %s, b is %b, c is %c" % (a, b, c)

        def bop(self, a):
          return "a is %s" % a

    and { "foo": Foo() } passed to the template, then:

      foo|method:"bar"|with:"one"|with:"two"|with:"three"|call

    will invoke foo("one", "two", "three"), and emit:

      a is one, b is two, c is three.

    Alternatively,

      foo|method:"bop"|call_with:"baz"

    is a bit of a short cut.
    """
    if hasattr(value, str(arg)):
        return getattr(value, str(arg))

    return "[%s has no method %s]" % (value, arg)

@register.filter
def call_with(value, arg):
    """
    Call a function with the specified argument.

    Meant to be used with the "method" tag.
    """
    if not callable(value):
        return "[%s is not callable]" % value

    return value(arg)

@register.filter
def call(value):
    """
    Call a function with no arguments.

    Meant to be used with the "method" tag.
    """
    if not callable(value):
        return "[%s is not callable]" % value

    return value()

@register.filter(name="with")
def with_(value, arg):
    """
    Accumulate the specified positional argument.

    Meant to be used with the "method" tag.
    """
    if callable(value):
        return partial(value, arg)

    return "[%s is not callable]" % value

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.