Ludicrously simple templates with Python
A long, long time ago I wrote my first ever PHP templating system. It was pretty simple; it consisted of a function that took two arguments: the name of a template file, and an associative array of replacements to make on that file.
I’ve finally got around to playing with Python CGIs for web development recently, and decided I needed a similar system. Thanks to Python’s powerful string formatting operator, it ended up as a one-liner:
def template(file, vars):
return open(templatedir.template, 'r').read() % vars
Presuming you’ve set templatedir at the top of the script, the above function lets you load a template and make some simple replacements on it with a single function call. For example:
<h3>%(title)s</h3>
%(body)s
<p class="footer">Posted: %(date)s</p>
With the above saved in the template directory as “entry.tpl”, the template function above can be used thus:
print template('entry.tpl', {
'title':'A blog entry',
'body':'Entry goes here...',
'date':'3rd July 2003'})
The work is all done by the % vars
bit at the end of the line. Since vars is a dictionary, Python substitutes the named items in the dictionary for their corresponding %(varname)s
tokens in the string loaded from the template file. More information on string formatting operations can be found in the manual.
As templating systems go, it’s far from the most useful or complete solution. It does however show that a little Python can go quite a long way.
More recent articles
- Lawyer cites fake cases invented by ChatGPT, judge is not amused - 27th May 2023
- llm, ttok and strip-tags - CLI tools for working with ChatGPT and other LLMs - 18th May 2023
- Delimiters won't save you from prompt injection - 11th May 2023
- Weeknotes: sqlite-utils 3.31, download-esm, Python in a sandbox - 10th May 2023
- Leaked Google document: "We Have No Moat, And Neither Does OpenAI" - 4th May 2023
- Midjourney 5.1 - 4th May 2023
- Prompt injection explained, with video, slides, and a transcript - 2nd May 2023
- download-esm: a tool for downloading ECMAScript modules - 2nd May 2023
- Let's be bear or bunny - 1st May 2023
- Weeknotes: Miscellaneous research into Rye, ChatGPT Code Interpreter and openai-to-sqlite - 1st May 2023