Commit 830f9fd9 by David Logie Committed by Chris Wanstrath

Higher Order Sections.

parent a15519f4
{{#replace_foo_with_bar}}
foo != bar. oh, it does!
{{/replace_foo_with_bar}}
\ No newline at end of file
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))
...@@ -67,7 +67,9 @@ class Template(object): ...@@ -67,7 +67,9 @@ class Template(object):
it = context.get(section_name, None) it = context.get(section_name, None)
replacer = '' 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 replacer = inner
elif it: elif it:
insides = [] insides = []
......
...@@ -3,6 +3,7 @@ import pystache ...@@ -3,6 +3,7 @@ import pystache
from examples.simple import Simple from examples.simple import Simple
from examples.complex_view import ComplexView from examples.complex_view import ComplexView
from examples.lambdas import Lambdas
class TestView(unittest.TestCase): class TestView(unittest.TestCase):
def test_basic(self): def test_basic(self):
...@@ -16,7 +17,7 @@ class TestView(unittest.TestCase): ...@@ -16,7 +17,7 @@ class TestView(unittest.TestCase):
def test_template_load(self): def test_template_load(self):
view = Simple(thing='world') view = Simple(thing='world')
self.assertEquals(view.render(), "Hi world!") self.assertEquals(view.render(), "Hi world!")
def test_template_load_from_multiple_path(self): def test_template_load_from_multiple_path(self):
path = Simple.template_path path = Simple.template_path
Simple.template_path = ('examples/nowhere','examples',) Simple.template_path = ('examples/nowhere','examples',)
...@@ -59,6 +60,21 @@ class TestView(unittest.TestCase): ...@@ -59,6 +60,21 @@ class TestView(unittest.TestCase):
</ul> </ul>
""") """)
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__': if __name__ == '__main__':
unittest.main() unittest.main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment