summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChris Wanstrath <chris@ozmm.org>2009-10-29 01:00:15 -0700
committerChris Wanstrath <chris@ozmm.org>2009-10-29 01:00:15 -0700
commit1bd85306567d828140c2def90bc14bae475d9f92 (patch)
tree2a8a72b1b0772b3f1c2869115c7316b6b202b3da
parentb51bd2e5e38703a42e3b858f93aea5b0146a2604 (diff)
downloadpystache-1bd85306567d828140c2def90bc14bae475d9f92.tar.gz
basic true / false sections
-rw-r--r--pystache/__init__.py16
-rw-r--r--tests/test_pystache.py30
2 files changed, 42 insertions, 4 deletions
diff --git a/pystache/__init__.py b/pystache/__init__.py
index 15f6620..a01b9f1 100644
--- a/pystache/__init__.py
+++ b/pystache/__init__.py
@@ -19,8 +19,24 @@ class Template(object):
"""Turns a Mustache template into something wonderful."""
template = template or self.template
context = context or self.context
+
+ template = self.render_sections(template, context)
return self.render_tags(template, context)
+ def render_sections(self, template, context):
+ regexp = re.compile(r"{{\#([^\}]*)}}\s*(.+?){{/\1}}")
+ match = re.search(regexp, template)
+
+ while match:
+ section, section_name, inner = match.group(0, 1, 2)
+ if section_name in context and context[section_name]:
+ return template.replace(section, inner)
+ else:
+ return template.replace(section, '')
+ match = re.search(regexp, template)
+
+ return template
+
def render_tags(self, template, context):
"""Renders all the tags in a template for a context."""
regexp = re.compile(r"{{(#|=|!|<|>|\{)?(.+?)\1?}}+")
diff --git a/tests/test_pystache.py b/tests/test_pystache.py
index c54bd72..dc7c023 100644
--- a/tests/test_pystache.py
+++ b/tests/test_pystache.py
@@ -21,7 +21,29 @@ class TestPystache(unittest.TestCase):
ret = Pystache.render(template)
self.assertEquals(ret, "What what?")
- def xtest_sections(self):
- template = "I think {{name}} wants a {{thing}}, right {{name}}?"
- ret = Pystache.render(template, { 'name': 'Jon', 'thing': 'racecar' })
- self.assertEquals(ret, "I think Jon wants a racecar, right Jon?")
+ def test_false_sections_are_hidden(self):
+ template = "Ready {{#set}}set {{/set}}go!"
+ ret = Pystache.render(template, { 'set': False })
+ self.assertEquals(ret, "Ready go!")
+
+ def test_true_sections_are_shown(self):
+ template = "Ready {{#set}}set{{/set}} go!"
+ ret = Pystache.render(template, { 'set': True })
+ self.assertEquals(ret, "Ready set go!")
+
+ def aaxtest_sections(self):
+ template = """
+<ul>
+ {{#users}}
+ <li>{{name}}</li>
+ {{/users}}
+</ul>
+"""
+
+ context = { 'users': [ {'name': 'Chris'}, {'name': 'Tom'}, {'name': 'PJ'} ] }
+ ret = Pystache.render(template, context)
+ self.assertEquals(ret, """<ul>
+ <li>Chris</li>
+ <li>Tom</li>
+ <li>PJ</li>
+</ul>""")