Last active
November 21, 2018 01:06
-
-
Save marceloandriolli/561c885c137c38fd15b5c5dc683da0a8 to your computer and use it in GitHub Desktop.
Simple email template tags
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
from string import Template | |
class DefaultTemplateTag(Template): | |
delimiter = '{{' | |
pattern = ''' | |
\{\{(?: | |
(?P<escaped>\{\{)| | |
(?P<named>[_a-z][_a-z0-9]*)\}\}| | |
(?P<braced>[_a-z][_a-z0-9]*)\}\}| | |
(?P<invalid>) | |
) | |
''' | |
class SimpleEmailTags: | |
def __init__(self, template=DefaultTemplateTag): | |
self.template = template | |
def _open_file(self, file_name): | |
with open(file_name) as file: | |
return file.read() | |
def _load_tags(self, html_string, tags): | |
return self.template(html_string).safe_substitute(tags) | |
def as_str(self, file_name, tags): | |
if not file_name and tags: | |
raise Exception('file and tags argument must be not None') | |
html_string = self._open_file(file_name) | |
return self._load_tags(html_string, tags) | |
""" | |
Usage: | |
content of base.html file: | |
<!DOCTYPE html> | |
<html> | |
<body> | |
<h1>Meu chamo {{nome}}</h1> | |
<p>Tenho {{idade}}</p> | |
</body> | |
</html> | |
>> content = SimpleEmailTags() | |
>> content.as_str('base.html', tag={'nome': 'Marcelo', 'idade': '33 anos'}) | |
>> '<!DOCTYPE html>\n<html>\n\n<body>\n\n <h1>Meu chamo Marcelo</h1>\n <p>Tenho 33 anos</p>\n\n</body>\n\n</html>' | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment