Python Mako template using dictionaries and arrays

Templating is a common technique used to avoid repetitive coding, also used to separate data from logic. Mako is one of the popular python template engines. In this tutorial I will show an example of Mako template that is used to constructs an "Invoice" form using dictionaries and arrays. Also a python script is given that can process this Mako template with dictionaries and arrays.


Purchase Details:

Product code: ${item_code}
Price: ${item_price}

Billing Address:
%for value in personal_info['location']:
%for value in personal_info['region'].values():

The following script processes the Mako template given above. Please note the script prepares all the necessary Invoice data and passes it as an augment to render function.

#! /usr/bin/python

from mako.template import Template

Invoice = {}
Invoice['item_code'] = "1234567"
Invoice['item_price'] = "100 uSD"
Invoice['personal_info'] = {'name':'Mr dude', 'location':['street1', 'place1'], 'region':{'country':'USA', 'state':'Texas', 'city':'austin'}}

OUT = Template(filename="invoice.mako").render(**Invoice)

print OUT

Running this script produces an output as shown bellow.

Purchase Details:

Product code: 1234567
Price: 100 uSD

Billing Address:
  Mr dude