PTML - Embed Python in text documents

[Python Powered]
Get PTML - Embed Python in documents. at SourceForge.net. Fast, secure and Free Open Source software downloads

Introduction to PTML

PTML lets you embed Python® code in text documents.

The rules are very simple:

  • text may contain expression fields starting with dollar sign and opening brace (${) and ending with closing brace (})
  • lines starting with percent sign (%) are Python code lines
  • line containing nothing but single percent sign ends Python structural block (decreases indent level)
  • <%python> starts Python code block. All lines until closing </%python> line are processed as Python code lines.
  • <%text> starts verbatim text block. PTML markup has no effect until closing </%text> line.
  • all other text of a template is copied to template output.

Example template:

%import time
Current time is ${time.ctime()}

<%python>
SCORES = (
    ("St Stephan", 29.9),
    ("Richard III", 29.3),
    ("Jean D'arc", 29.1),
    ("Marat", 29.0),
    ("A. Lincoln (U.S of A)", 28.2),
    ("G. Khan", 28.1),
    ("King Edward VII", 3.1),
)
</%python>
You can see the scores now:

%for name, score in SCORES:
   ${"%22s" % name} : ${score}
%

Output produced by above template:

Current time is Sat Dec 03 18:03:58 2005

You can see the scores now:

               St Stephan : 29.9
              Richard III : 29.3
               Jean D'arc : 29.1
                    Marat : 29.0
    A. Lincoln (U.S of A) : 28.2
                  G. Khan : 28.1
          King Edward VII : 3.1

How it works

The core of the PTML package is TemplateParser module. TemplateParser reads template text and writes a Python program. Execution of this program produces template output.

Here is the program created from the above template:

import time
stdout.write('Current time is ')
stdout.write(str(time.ctime()))
stdout.write('\n')
stdout.write('\n')
SCORES = (
    ("St Stephan", 29.9),
    ("Richard III", 29.3),
    ("Jean D'arc", 29.1),
    ("Marat", 29.0),
    ("A. Lincoln (U.S of A)", 28.2),
    ("G. Khan", 28.1),
    ("King Edward VII", 3.1),
)
stdout.write('You can see the scores now:\n')
stdout.write('\n')
#
# word=for, dedent=[]
#
for name, score in SCORES:
        stdout.write('   ')
        stdout.write(str("%22s" % name))
        stdout.write(' : ')
        stdout.write(str(score))
        stdout.write('\n')

Simple Python script running a template:

import sys
from cStringIO import StringIO
from ptml.TemplateParser import TemplateParser

template = file("scores.ptml")
code = StringIO()
TemplateParser(template, code).parse()
template.close()

exec code.getvalue() in {"stdout": sys.stdout}

And now...

There's more than just template parsing. PTML includes template manager (AutoParser module) and ptml-enabled HTTP server. Unfortunately, they are not documented yet. Please look at the sources.


Python® and the Python logos are trademarks or registered trademarks of the Python Software Foundation.