diff --git a/examples/lambdas.mustache b/examples/lambdas.mustache new file mode 100644 index 0000000..7eb4ea2 --- /dev/null +++ b/examples/lambdas.mustache @@ -0,0 +1,3 @@ +{{#replace_foo_with_bar}} + foo != bar. oh, it does! +{{/replace_foo_with_bar}} \ No newline at end of file diff --git a/examples/lambdas.py b/examples/lambdas.py new file mode 100644 index 0000000..01a3697 --- /dev/null +++ b/examples/lambdas.py @@ -0,0 +1,30 @@ +import pystache + +def rot(s, n=13): + r = "" + for c in s: + cc = c + if cc.isalpha(): + cc = cc.lower() + o = ord(cc) + ro = (o+n) % 122 + if ro == 0: ro = 122 + if ro < 97: ro += 96 + cc = chr(ro) + r = ''.join((r,cc)) + return r + +def replace(subject, this='foo', with_this='bar'): + return subject.replace(this, with_this) + +class Lambdas(pystache.View): + template_path = 'examples' + + def replace_foo_with_bar(self, text=None): + return replace + + def rot13(self, text=None): + return rot + + def sort(self, text=None): + return lambda text: ''.join(sorted(text)) diff --git a/pystache/template.py b/pystache/template.py index 75bf7a6..d8220cb 100644 --- a/pystache/template.py +++ b/pystache/template.py @@ -67,7 +67,9 @@ class Template(object): it = context.get(section_name, None) replacer = '' - if it and not hasattr(it, '__iter__'): + if it and hasattr(it, '__call__'): + replacer = it(inner) + elif it and not hasattr(it, '__iter__'): replacer = inner elif it: insides = [] diff --git a/tests/test_view.py b/tests/test_view.py index d0e2968..bcdbb90 100644 --- a/tests/test_view.py +++ b/tests/test_view.py @@ -3,6 +3,7 @@ import pystache from examples.simple import Simple from examples.complex_view import ComplexView +from examples.lambdas import Lambdas class TestView(unittest.TestCase): def test_basic(self): @@ -16,7 +17,7 @@ class TestView(unittest.TestCase): def test_template_load(self): view = Simple(thing='world') self.assertEquals(view.render(), "Hi world!") - + def test_template_load_from_multiple_path(self): path = Simple.template_path Simple.template_path = ('examples/nowhere','examples',) @@ -59,6 +60,21 @@ class TestView(unittest.TestCase): """) + def test_higher_order_replace(self): + view = Lambdas() + self.assertEquals(view.render(), + 'bar != bar. oh, it does!') + + def test_higher_order_rot13(self): + view = Lambdas() + view.template = '{{#rot13}}abcdefghijklm{{/rot13}}' + self.assertEquals(view.render(), 'nopqrstuvwxyz') + + def test_higher_order_lambda(self): + view = Lambdas() + view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}' + self.assertEquals(view.render(), 'abcdefghijklmnopqrstuvwxyz') + if __name__ == '__main__': unittest.main()