Created
January 23, 2014 05:59
-
-
Save sokrato/8573658 to your computer and use it in GitHub Desktop.
simple Python Template Engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- 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