Skip to content

Instantly share code, notes, and snippets.

@csrgxtu
Created July 3, 2017 07:00
Show Gist options
  • Save csrgxtu/210508cb1632bb7ec1b095553ba25221 to your computer and use it in GitHub Desktop.
Save csrgxtu/210508cb1632bb7ec1b095553ba25221 to your computer and use it in GitHub Desktop.
a very simple template engine based on string.format
import string
class SuperFormatter(string.Formatter):
"""World's simplest Template engine."""
def format_field(self, value, spec):
if spec.startswith('repeat'):
template = spec.partition(':')[-1]
if type(value) is dict:
value = value.items()
return ''.join([template.format(item=item) for item in value])
elif spec == 'call':
return value()
elif spec.startswith('if'):
return (value and spec.partition(':')[-1]) or ''
else:
return super(SuperFormatter, self).format_field(value, spec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment