mirror of
https://github.com/kennethreitz-archive/pystache.git
synced 2026-06-05 23:40:16 +00:00
Higher Order Sections.
This commit is contained in:
committed by
Chris Wanstrath
parent
a15519f43b
commit
830f9fd964
@@ -0,0 +1,3 @@
|
||||
{{#replace_foo_with_bar}}
|
||||
foo != bar. oh, it does!
|
||||
{{/replace_foo_with_bar}}
|
||||
@@ -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))
|
||||
@@ -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 = []
|
||||
|
||||
+17
-1
@@ -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):
|
||||
</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__':
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user