diff --git a/pystache/template.py b/pystache/template.py index 56a717a..dd4ecee 100644 --- a/pystache/template.py +++ b/pystache/template.py @@ -1,6 +1,21 @@ import re import cgi +modifiers = {} +def modifier(symbol): + """Decorator for associating a function with a Mustache tag modifier. + + @modifier('P') + def render_tongue(self, tag_name=None, context=None): + return ":P %s" % tag_name + + {{P yo }} => :P yo + """ + def set_modifier(func): + modifiers[symbol] = func + return func + return set_modifier + class Template(object): # The regular expression used to find a #section section_re = None @@ -14,15 +29,6 @@ class Template(object): # Closing tag delimiter ctag = '}}' - # Names of different tag modifiers, used to render them. - tag_types = { - None: 'tag', - '!': 'comment', - '{': 'unescaped', - '>': 'partial', - '=': 'delimiter' - } - def __init__(self, template, context=None): self.template = template self.context = context or {} @@ -79,26 +85,28 @@ class Template(object): tag, tag_type, tag_name = match.group(0, 1, 2) tag_name = tag_name.strip() - func = 'render_' + self.tag_types[tag_type] - - if hasattr(self, func): - replacement = getattr(self, func)(tag_name, context) - template = template.replace(tag, replacement) + func = modifiers[tag_type] + replacement = func(self, tag_name, context) + template = template.replace(tag, replacement) return template + @modifier(None) def render_tag(self, tag_name, context): """Given a tag name and context, finds, escapes, and renders the tag.""" return cgi.escape(context.get(tag_name, '')) + @modifier('!') def render_comment(self, tag_name=None, context=None): """Rendering a comment always returns nothing.""" return '' + @modifier('{') def render_unescaped(self, tag_name=None, context=None): """Render a tag without escaping it.""" return context.get(tag_name, '') + @modifier('>') def render_partial(self, tag_name=None, context=None): """Renders a partial within the current context.""" # Import view here to avoid import loop @@ -109,6 +117,7 @@ class Template(object): return view.render() + @modifier('=') def render_delimiter(self, tag_name=None, context=None): """Changes the Mustache delimiter.""" self.otag, self.ctag = tag_name.split(' ')