Commit 9c0b9291 by David Logie Committed by Chris Wanstrath

Inverted sections.

parent 830f9fd9
{{^f}}one{{/f}}, {{ two }}, {{^f}}three{{/f}}{{^t}}, four!{{/t}}
\ No newline at end of file
import pystache
class Inverted(pystache.View):
template_path = 'examples'
def t(self):
return True
def f(self):
return False
def two(self):
return 'two'
...@@ -49,7 +49,7 @@ class Template(object): ...@@ -49,7 +49,7 @@ class Template(object):
"""Compiles our section and tag regular expressions.""" """Compiles our section and tag regular expressions."""
tags = { 'otag': re.escape(self.otag), 'ctag': re.escape(self.ctag) } tags = { 'otag': re.escape(self.otag), 'ctag': re.escape(self.ctag) }
section = r"%(otag)s\#([^\}]*)%(ctag)s\s*(.+?)\s*%(otag)s/\1%(ctag)s" section = r"%(otag)s[\#|^]([^\}]*)%(ctag)s\s*(.+?)\s*%(otag)s/\1%(ctag)s"
self.section_re = re.compile(section % tags, re.M|re.S) self.section_re = re.compile(section % tags, re.M|re.S)
tag = r"%(otag)s(#|=|&|!|>|\{)?(.+?)\1?%(ctag)s+" tag = r"%(otag)s(#|=|&|!|>|\{)?(.+?)\1?%(ctag)s+"
...@@ -70,12 +70,15 @@ class Template(object): ...@@ -70,12 +70,15 @@ class Template(object):
if it and hasattr(it, '__call__'): if it and hasattr(it, '__call__'):
replacer = it(inner) replacer = it(inner)
elif it and not hasattr(it, '__iter__'): elif it and not hasattr(it, '__iter__'):
replacer = inner if section[2] != '^':
replacer = inner
elif it: elif it:
insides = [] insides = []
for item in it: for item in it:
insides.append(self.render(inner, item)) insides.append(self.render(inner, item))
replacer = ''.join(insides) replacer = ''.join(insides)
elif not it and section[2] == '^':
replacer = inner
template = template.replace(section, replacer) template = template.replace(section, replacer)
......
...@@ -4,6 +4,7 @@ import pystache ...@@ -4,6 +4,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 from examples.lambdas import Lambdas
from examples.inverted import Inverted
class TestView(unittest.TestCase): class TestView(unittest.TestCase):
def test_basic(self): def test_basic(self):
...@@ -75,6 +76,10 @@ class TestView(unittest.TestCase): ...@@ -75,6 +76,10 @@ class TestView(unittest.TestCase):
view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}' view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}'
self.assertEquals(view.render(), 'abcdefghijklmnopqrstuvwxyz') self.assertEquals(view.render(), 'abcdefghijklmnopqrstuvwxyz')
def test_inverted(self):
view = Inverted()
self.assertEquals(view.render(), """one, two, three""")
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