Introducing the Proton Template Engine (part 2)
In a typical template engine, there will be some form of conditional logic, for changing the display of a section of a document. This will generally be an if-statement wrapping one or more elements, perhaps enabling or disabling sections based on access rights, showing more detail based on data, and so on.
Proton supports this logic with the facility to hide an element (marked with the eid attribute). For example, in this excerpt of a navigation menu:
<ul class="menu">
<li eid="accounts"><a href="/accounts">Account Summary</a></li>
<li eid="transactions"><a href="/transactions">View / Download Transactions</a></li>
<li eid="transfer"><a href="/transfer">Transfer Funds</a></li>
<li eid="bills"><a href="/bills">Bill Payments</a></li>
<li eid="autopayments"><a href="/autopayments">Automatic Payments</a></li>
<li eid="exchange"><a href="/exchange">Foreign Exchange</a></li>
</ul>
The following code will switch off the “transactions”, “autopayments” and “exchange” elements:
tmp.hide('autopayments')
tmp.hide('exchange')
tmp.hide('transactions')
Resulting in output of:
<ul class="menu">
<li><a href="/accounts">Account Summary</a></li>
<li><a href="/transfer">Transfer Funds</a></li>
<li><a href="/bills">Bill Payments</a></li>
</ul>
You can see this example in action in the test hiding.py.
Another, less common but equally useful, feature of template engines is the facility to translate text (in other words, i18n or the internationalisation of output). Proton supports translation by setting a translation function on a template. For example, consider the following template:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Page Title</h1>
<p id="para1">Some translated text</p>
<p id="para2">Not translated text</p>
</body>
</html>
In this case, translation doesn’t rely on the 3 attributes (eid, aid, rid) — rather a default set of named (xhtml) elements are translated (the set can, of course, be overridden). The following code demonstrates translation in action:
fr = {
'Page Title' : 'Titre de la page',
'Some translated text' : 'Certains textes traduits'
}
def translate(text):
if text in fr:
return fr[text]
else:
return text
tmp = self.templates['tests/i18n.xhtml']
tmp.translate = translate
And the resulting output:
<html>
<head>
<title>Titre de la page</title>
</head>
<body>
<h1>Titre de la page</h1>
<p id="para1">Certains textes traduits</p>
<p id="para2">Not translated text</p>
</body>
</html>


