Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add stupid templates.

  • Loading branch information...
commit d6726bf28f6879b923f3474aec56c82a8b7c5563 1 parent 119aabe
@SimonSapin authored
Showing with 65 additions and 1 deletion.
  1. +1 −1  LICENSE
  2. +64 −0 stupid_templates.py
View
2  LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2011 by Simon Sapin.
+Copyright (c) 2011-2013 by Simon Sapin.
Some rights reserved.
View
64 stupid_templates.py
@@ -0,0 +1,64 @@
+"""A stupidly simple, unsafe, and inefficient template engine."""
+
+import re
+
+
+def parse(source):
+ root = nodes = []
+ stack = []
+ while 1:
+ text, delim, source = source.partition('{%')
+ nodes.append(('text', text))
+ if not delim:
+ return root
+ code, _, source = source.partition('%}')
+ code = code.strip()
+
+ match = re.match('for\s+(\w+)\s+in\s+(.+)', code)
+ if match:
+ item_name, expr = match.groups()
+ child_nodes = []
+ nodes.append(('for', (item_name, expr, child_nodes)))
+ stack.append(nodes)
+ nodes = child_nodes
+ continue
+
+ match = re.match('if\s+(.+)', code)
+ if match:
+ expr, = match.groups()
+ child_nodes = []
+ nodes.append(('if', (expr, child_nodes)))
+ stack.append(nodes)
+ nodes = child_nodes
+ continue
+
+ assert code == 'end'
+ nodes = stack.pop()
+
+
+def render(nodes, context, write):
+ for node_type, value in nodes:
+ if node_type == 'text':
+ write(value.format(**context))
+ elif node_type == 'for':
+ item_name, expr, child_nodes = value
+ for value in eval(expr, context, context):
+ inner_context = context.copy()
+ inner_context[item_name] = value
+ render(child_nodes, inner_context, write)
+ elif node_type == 'if':
+ expr, child_nodes = value
+ if eval(expr, context, context):
+ render(child_nodes, context, write)
+ else:
+ assert 0, node_type
+
+
+if __name__ == '__main__':
+ import sys
+ render(parse('''
+ {foo}
+ {% for i in bar %}
+ [{i}]
+ {% if i == 'abc' %}{% for c in i %}{c} {% end %}
+ '''), dict(foo=4, bar=[-2, 'abc', 'baz']), sys.stdout.write)
Please sign in to comment.
Something went wrong with that request. Please try again.