Mako Templates for Python

Mako is a template library written in Python.

Basic Usage

from mako.template import Template

mytemplate = Template("Hello, ${name}!")
print(mytemplate.render(name="John"))

Using File-Based Templates

from mako.template import Template
from mako.lookup import TemplateLookup

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age


studentList = []
studentList.append(Student("Alex", 20))
studentList.append(Student("Bob", 21))
studentList.append(Student("Ira", 15))

# TemplateLookup
mylookup = TemplateLookup(directories=['D:/'], module_directory='C:/tmp/mako')

mt = Template(filename='D:/mako/tp/Album.txt', module_directory='C:/tmp/mako'
, output_encoding='utf-8'
, lookup=mylookup)

sHtml = mt.render(objects=studentList)
# print(sHtml)

# to save the results
with open("test.htm", "wb") as fh:
    fh.write(sHtml)

Mako Templates

<html>
<head>
<%include file="header.htm"/>
</head>
<body>
%for o in objects:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
	<b>Name:</b>
</td>
</tr>
<tr>
<td>
	${ o.name or '' } ${ o.age }
</td>
</tr>
</table>
%endfor
</body>
<%include file="footer.htm"/>
</html>