Created
July 3, 2017 07:00
-
-
Save csrgxtu/210508cb1632bb7ec1b095553ba25221 to your computer and use it in GitHub Desktop.
a very simple template engine based on string.format
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
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