Using callable classes with @contextfunction #180

Closed
Naddiseo opened this Issue Feb 18, 2013 · 1 comment

Comments

1 participant

A class with a call attribute should be able to take a context via @contextfunction

Testcase:

from jinja2 import Environment, FileSystemLoader
from jinja2.utils import contextfunction

env  = Environment(loader=FileSystemLoader(''))

class Adder(object):
    def __init__(self, lhs):
        self.lhs = lhs

    @contextfunction
    def __call__(self, context, rhs):
        other = context.resolve('other')

        if not other:
            other = 0

        return other + lhs + rhs

t = env.from_string("""
1 + 2 + 3
Should be: 6
Result is: {{ adder(2) }}
""")

print t.render({'adder' : Adder(2), 'other' : 1})

In case anyone else runs into this before it's fixed I've come up with a work around:

def context_class_hack(klass):
    def inner(*args, **kwargs):
        instance = klass(*args, **kwargs)

        @contextfunction
        def klass_wrapper(context, *args, **kwargs):
            return instance(context, *args, **kwargs)
        return klass_wrapper

    return inner

# Usage:
@context_class_hack
class Klass(object):
    def __call__(self, context, *args, **kwargs):
        return

@mitsuhiko mitsuhiko closed this in 9952041 May 18, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment