Skip to content

Instantly share code, notes, and snippets.

@sokrato
Created January 23, 2014 05:59
Show Gist options
  • Save sokrato/8573658 to your computer and use it in GitHub Desktop.
Save sokrato/8573658 to your computer and use it in GitHub Desktop.
simple Python Template Engine
#-*- coding: utf8 -*-
from __future__ import print_function
import re
def format(tpl, **vars):
p = re.compile(r'''\{\{\s*([a-zA-Z0-9_]+?)\s*\}\}''')
ret, pos = '', 0
while True:
match = p.search(tpl, pos)
if not match:
ret += tpl[pos:]
break
ret += tpl[match.pos: match.start()]
ret += str(vars.get(match.group(1), ''))
pos = match.end()
return ret
tpl = 'hello, {{ name }} ! {{ age }} years old.{{extra}} -- end!'
vars = {'name': 'xuxiang', 'age': 27}
print(format(tpl, **vars))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment