Last active
January 15, 2022 21:57
-
-
Save techtonik/3d49a33530f51b71fa9a to your computer and use it in GitHub Desktop.
Template engine that knows how to render {{ tag }}
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
# minijinja is in public domain | |
class MiniJinja(object): | |
""" Template engine that knows how to render {{ tag }} """ | |
def __init__(self, templates='.'): | |
"""templates - template path""" | |
import re | |
import sys | |
self.PY3K = sys.version_info[0] == 3 | |
self.path = templates + '/' | |
self.tag = re.compile('{{ *(?P<tag>\w+) *}}') | |
def render(self, template, vardict=None, **kwargs): | |
"""returns unicode str""" | |
data = vardict or {} | |
data.update(kwargs) | |
def lookup(match): | |
return data[match.group('tag')] | |
tpl = open(self.path + template).read() | |
if not self.PY3K: | |
return unicode(self.tag.sub(lookup, tpl)) | |
else: | |
return self.tag.sub(lookup, tpl) | |
if __name__ == '__main__': | |
jinjer = MiniJinja('templates') | |
d = dict(body='Hello, World!') | |
jinjer.render('index.tpl', d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment