Commit 1bd85306 by Chris Wanstrath

basic true / false sections

parent b51bd2e5
......@@ -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?}}+")
......
......@@ -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>""")
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