Last updated:
0 purchases
pythontemplet 4.0.0
# Python Templating with @templetHere is an elegant lightweight python templating module that supports inline python, speedy compilation, subtemplates, and subclassing, all in a simple decorator module implemented in about 125 lines of python.## What's NewTemplet was created by David Bau, and modifications for version 4 are by Krisztián Fekete. Version 4 adds: * Python 3 support. * Proper unit tests, verifying python2, python3, and pypy support. * Support only unicode strings (no bytestrings). * Removed special case for empty-first-newline. * Cleaned up code for readability.## UsageTo use templet, just annotate a python function with @templet, and then put the template text where the docstring would normally be. Leave the function body empty, and efficient code to concatenate the contents will be created.``` from templet import templet @templet def myTemplate(animal, body): "the animaljumpedoverthebody." print(myTemplate('cow', 'moon'))```This is turned into something like this:``` def myTemplate(animal, body): out = [] out.append("the ") out.append(str(animal)) out.append(" jumped over the ") out.append(str(body)) out.append(".") return ''.join(out)```There are just six constructs that are supported, all starting with :|syntax|meaning||−−−−−−−−|−−−−−−−−−||‘myvar` | inserts the value of the variable `myvar` || `...‘|evaluatestheexpressionandinsertstheresult||‘{[...]}` | runs a list comprehension and concatenates the results || `...‘|executesenclosedcode;use‘out.append(text)‘toinserttext||‘‘|anescapeforasingle‘` || `‘|(attheendoftheline)isalinecontinuation|Allordinaryusesof‘` in the template need to be escaped by doubling the `$$` - with the exception of (as mentioned above) `.‘,‘(`, `/‘,‘'`, and `You can't use 'macro parameter character #' in math modeYou can't use 'macro parameter character #' in math mode{"%2.3f" % num}`; if you want to escape HTML sequences, just write `cgi.escape(message)‘.Notasbriefasaspecializedsyntax,buteasytoremember,briefenough,andreadabletoanypythonprogrammer.Similarly,templetdoesnotinventanynewcontrolfloworloopingstructures.Toloopatemplate,youneedtouseapythonlooporlistcomprensionandcallthesubtemplateasafunction:‘‘‘@templetdefdoctemplate(table):""" <body><h1>{ table.name }</h1> <table> foritemintable:out.append(self.rowtemplate(item))</table></body>"""‘‘‘Ifyoupreferlistcomprehensions,itisslightlymorebrief:‘‘‘@templetdefdoctemplate(table):""" <body><h1>{ table.name }</h1> <table> You can't use 'macro parameter character #' in math modeYou can't use 'macro parameter character #' in math mode` at the end of a line for a line continuation.So my recommended style for multiline templates is: * indent template text in the function as if it were python code. * use a python triple-quote and put the opening quote on its own line. * never indent HTML tags - they just get too deep, so put them all at column 0. * when nesting gets confusing, for readability, just put one tag on each line. * liberally use `‘continuationsiflayoutdemandsno−whitespace.∗indentcodeinside‘{{` and then put `}}` on its own line (a newline right after a closing `}}` is eaten).Relative indenting for python code inside `...‘ispreservedusingthesameleading−space−strippingtrickasisusedforthetemplatesthemselves,soyoucanindentembeddedpythonasnormal,andyoucanstarttheindentingatwhichevercolumnfeelsnatural.Iusuallyindentembeddedpythonbyonemorelevel.Intheunusualcasewhereitisnecessarytoemittextthathasleadingspacesoneveryline,youcanbeginthetemplatewithacontinuationlinewiththe‘` in the column that you want to treat as column zero, as follows:```@templetdef indented(x): """\ varvalxx """```One question is whether the opening `"""` should be on the same line as the def or its own line. For clarity I usually put the opening quote on its own line, but to get columns to line up correctly, I eat the newline with a python line continuation immediately `"""\`.For example, if you want to achieve all on one line the following:```<tr><td class="..."><a class="..." href="/foo/bar/...">....</a></td><td class="...">...</td></tr>```Then you could use:```@templetdef table_row(row_data): """\ <tr><tdclass="{col1_class} def"><aclass="{link_class}"href="/foo/bar/{cgi.escape(filename, True)}">{cgi.escape(link_text})}</a> </td><tdclass="{col2_class}">{{ if (enrolled): out.append('enrolled') }} cgi.escape(labeltext) </td>$ </tr> """```
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.