Created
September 23, 2015 17:59
-
-
Save iLoveTux/5680d75988b8dcc8ceec to your computer and use it in GitHub Desktop.
Extremely simple Python Templating Engine
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
""" | |
# template.py | |
Extremely simple Python Templating Engine | |
This is a no-frills templating engine written in Python. I chose to | |
write this when I decided that I wanted something that was extremely | |
simple templating system and even str.format seemed like overkill. | |
You can use either a string as a template, or a file. NOTE, however, | |
that the file will be read entirely into memory, so if working with | |
large files you should either iterate through it yourself or use a more | |
fully-featured templating engine (I would probably recomend Jinja2). | |
to use a string as a template use render_template, and to use a file | |
use render_template_file. | |
""" | |
def render_template(string, mapping): | |
""" | |
## render_template | |
given string and mapping where string is a Python string | |
and mapping is a hasable object (such as a dict), any | |
occurances of <%key_name%> will be replaced with the | |
value associated with key_name within mapping. for | |
example: | |
>>> m = {"name": "ilovetux", "sex": "male"} | |
>>> s = "Hello, my name is <%name%> and I am <%sex%>." | |
>>> print render_template(s, m) | |
Hello, my name is ilovetux and I am male. | |
""" | |
for k, v in mapping.items(): | |
string = string.replace("<%{}%>".format(k), v) | |
return string | |
def render_template_file(fname, mapping): | |
""" | |
render_template_file | |
NOTE: file fname will be read entirely into memory, so you | |
probably shouldn't use this on large files. | |
given fname and mapping where fname is a string containing | |
a filename and mapping is a hasable object (such as a dict), | |
any occurances of <%key_name%> will be replaced with the | |
value associated with key_name within mapping. for | |
example: | |
in file /tmp/text.html | |
``` | |
<h1>hello, my name is <%name%></h1> | |
<h2>I am <%sex%></h2> | |
``` | |
>>> m = {"name": "ilovetux", "sex": "male"} | |
>>> print render_template_file("/tmp/text.html") | |
<h1>hello, my name is ilovetux</h1> | |
<h2>I am male</h2> | |
""" | |
with open(fname, "r") as fin: | |
ret = render_template(fin.read(), mapping) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment