Commit b51bd2e5 by Chris Wanstrath

more tests, more code

parent 63d74784
......@@ -2,27 +2,50 @@ import re
class Pystache(object):
@staticmethod
def render(template, context):
def render(template, context={}):
return Template(template, context).render()
class Template(object):
tag_types = {
None: 'tag',
'!': 'comment'
}
def __init__(self, template, context={}):
self.template = template
self.context = context
def render(self):
return self.render_tags()
def render(self, template=None, context=None):
"""Turns a Mustache template into something wonderful."""
template = template or self.template
context = context or self.context
return self.render_tags(template, context)
def render_tags(self):
def render_tags(self, template, context):
"""Renders all the tags in a template for a context."""
regexp = re.compile(r"{{(#|=|!|<|>|\{)?(.+?)\1?}}+")
template = self.template
match = re.search(regexp, template)
while match:
tag, tag_name = match.group(0, 2)
if tag_name in self.context:
template = template.replace(tag, self.context[tag_name])
tag, tag_type, tag_name = match.group(0, 1, 2)
func = 'render_' + self.tag_types[tag_type]
if hasattr(self, func):
replacement = getattr(self, func)(tag_name, context)
template = template.replace(tag, replacement)
match = re.search(regexp, template)
return template
def render_tag(self, tag_name, context):
"""Given a tag name and context, finds and renders the tag."""
if tag_name in context:
return context[tag_name]
else:
return ''
def render_comment(self, tag_name=None, context=None):
"""Rendering a comment always returns nothing."""
return ''
......@@ -7,8 +7,21 @@ class TestPystache(unittest.TestCase):
self.assertEquals(ret, "Hi world!")
def test_less_basic(self):
template = """It's a nice day for {{beverage}}, right {{person}}?"""
template = "It's a nice day for {{beverage}}, right {{person}}?"
ret = Pystache.render(template, { 'beverage': 'soda', 'person': 'Bob' })
self.assertEquals(ret, "It's a nice day for soda, right Bob?")
def test_even_less_basic(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_comments(self):
template = "What {{! the }} what?"
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?")
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