From 9c0b92919ac0007a22b31578bdd63d5cfa460979 Mon Sep 17 00:00:00 2001 From: David Logie Date: Sat, 1 May 2010 22:01:43 +0800 Subject: Inverted sections. --- examples/inverted.mustache | 1 + examples/inverted.py | 13 +++++++++++++ pystache/template.py | 7 +++++-- tests/test_view.py | 5 +++++ 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 examples/inverted.mustache create mode 100644 examples/inverted.py diff --git a/examples/inverted.mustache b/examples/inverted.mustache new file mode 100644 index 0000000..6e85f3e --- /dev/null +++ b/examples/inverted.mustache @@ -0,0 +1 @@ +{{^f}}one{{/f}}, {{ two }}, {{^f}}three{{/f}}{{^t}}, four!{{/t}} \ No newline at end of file diff --git a/examples/inverted.py b/examples/inverted.py new file mode 100644 index 0000000..1895050 --- /dev/null +++ b/examples/inverted.py @@ -0,0 +1,13 @@ +import pystache + +class Inverted(pystache.View): + template_path = 'examples' + + def t(self): + return True + + def f(self): + return False + + def two(self): + return 'two' diff --git a/pystache/template.py b/pystache/template.py index d8220cb..d232dad 100644 --- a/pystache/template.py +++ b/pystache/template.py @@ -49,7 +49,7 @@ class Template(object): """Compiles our section and tag regular expressions.""" 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) tag = r"%(otag)s(#|=|&|!|>|\{)?(.+?)\1?%(ctag)s+" @@ -70,12 +70,15 @@ class Template(object): if it and hasattr(it, '__call__'): replacer = it(inner) elif it and not hasattr(it, '__iter__'): - replacer = inner + if section[2] != '^': + replacer = inner elif it: insides = [] for item in it: insides.append(self.render(inner, item)) replacer = ''.join(insides) + elif not it and section[2] == '^': + replacer = inner template = template.replace(section, replacer) diff --git a/tests/test_view.py b/tests/test_view.py index bcdbb90..19ade99 100644 --- a/tests/test_view.py +++ b/tests/test_view.py @@ -4,6 +4,7 @@ import pystache from examples.simple import Simple from examples.complex_view import ComplexView from examples.lambdas import Lambdas +from examples.inverted import Inverted class TestView(unittest.TestCase): def test_basic(self): @@ -75,6 +76,10 @@ class TestView(unittest.TestCase): view.template = '{{#sort}}zyxwvutsrqponmlkjihgfedcba{{/sort}}' self.assertEquals(view.render(), 'abcdefghijklmnopqrstuvwxyz') + def test_inverted(self): + view = Inverted() + self.assertEquals(view.render(), """one, two, three""") + if __name__ == '__main__': unittest.main() -- cgit v1.2.1