Created
January 9, 2014 22:15
-
-
Save cameronp98/8343092 to your computer and use it in GitHub Desktop.
Almost useful template 'engine' in Python
This file contains hidden or 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 re | |
import hashlib | |
class TemplateError(Exception): | |
pass | |
class Template(object): | |
pattern = r"(\{[a-zA-Z0-9-_\|\.]+\})" | |
def __init__(self, string): | |
self.string = string | |
def run(self, **kwargs): | |
matches = re.findall(self.pattern, self.string) | |
if not matches: return self.string | |
tokens = [i[1:-1].split("|") for i in matches] | |
for i,match in enumerate(matches): | |
token = tokens[i] | |
# assumes that argument is supplied | |
value_s = token[0].split(".") # separate objects/attrs | |
value = kwargs[value_s[0]] | |
# if value has attributes get 'em | |
if len(value_s) > 1: | |
if type(value) == dict: | |
value = value[value_s[1]] | |
else: | |
value = getattr(value, value_s[1]) | |
# if modifiers are present apply them | |
if len(token) > 1: | |
for function in token[1:]: | |
# assumes function is defined | |
value = getattr(self, function)(value) | |
self.string = self.string.replace(match, value) | |
return self.string | |
def downcase(self, string): | |
return string.lower() | |
def upcase(self, string): | |
return string.upper() | |
def reverse(self, string): | |
return string[::-1] | |
def cap_words(self, string): | |
return string.title() | |
def cap_first(self, string): | |
return string.capitalize() | |
def md5(self, string): | |
return hashlib.md5(string.encode()).hexdigest() | |
def sha1(self, string): | |
return hhashlib.sha1(string.encode()).hexdigest() | |
def base2(self, string): | |
return " ".join([str(bin(ord(c)))[2:] for c in string]) | |
def base16(self, string): | |
return " ".join([str(hex(ord(c)))[2:] for c in string]) | |
def isdowncase(self, string): | |
return str(string.islower().real) | |
def isupcase(self, string): | |
return str(string.upper().real) | |
def isnumeric(self, string): | |
return str(string.isnumeric().real) | |
def isalpha(self, string): | |
return str(string.isalpha().real) | |
if __name__ == '__main__': | |
t = Template("'cameron' in binary = '{name|upcase|base2}'").run(name="cameron") | |
print(t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment