Weblog » Introducing Normal Template for Python
Normal Template is a template engine originally developed by my friend George Moschovitis in JavaScript. What I really like about Normal Template is its simplicity, compactness and its clean JSON-ish approach.
Therefore, I decided to write a Python port and use it as an alternative out-of-the-box template engine for the upcoming release of Porcupine. Normal templates are safe, applicable to any non XML/HTML contexts and portable to any programming language.
Sample usage:
template.html
<html>
<h1>Hello {=name}</h1>
{:select profile}
<p>
{=age}<br/>
{=gender}<br/>
</p>
{/:select}
<p>Your age is {=profile/age}</p>
<ul>
{:reduce articles}
<li>{=title} - {=count}</li>
{:else}
<li>No articles found</li>
{/:reduce}
</ul>
{:if admin}
You have admin rights
{:else}
You don't have admin rights
{/:if}
</html>
template.py
from normaltemplate import *
template_file = open('template.html')
src = template_file.read().decode('utf-8')
template_file.close()
# compile template into a Python function
template = compile(src)
data = { // the data dictionary in JSON format
'name' : 'George',
'profile' : {
'age' : 34,
'gender' : 'M'
},
'articles' : [
{ 'title' : 'Hello world', 'count' : 34 },
{ 'title' : 'Another article', 'count' : 23 },
{ 'title' : 'The final', 'count' : 7 }
],
'admin': True
}
# calling the template with the data dictionary
# returns the rendered output
print(template(data))
The code for py-normal-template is available on github at http://github.com/tkouts/py-normal-template. The original JavaScript implementation is available at http://github.com/gmosx/normal-template.