Inside the document, Python code needs to be surrounded by "<%" and "%>". Python expressions are enclosed in "<%=" and "%>". A directive can be enclosed in "<%@" and "%>". A comment (which will never be part of the resulting code) can be enclosed in "<%-" and "-%>"
Here is a primitive PSP page that demonstrated use of both code and expression embedded in an HTML document:
<html> <% import time %> Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%> </html>
Internally, the PSP parser would translate the above page into the following Python code:
req.write("""<html> """) import time req.write(""" Hello world, the time is: """); req.write(str(time.strftime("%Y-%m-%d, %H:%M:%S"))); req.write(""" </html> """)
This code, when executed inside a handler would result in a page displaying words "Hello world, the time is: " followed by current time.
Python code can be used to output parts of the page conditionally or in loops. Blocks are denoted from within Python code by indentation. The last indentation in Python code (even if it is a comment) will persist through the document until either end of document or more Python code.
Here is an example:
<html> <% for n in range(3): # This indent will persist %> <p>This paragraph will be repeated 3 times.</p> <% # This line will cause the block to end %> This line will only be shown once.<br> </html>
The above will be internally translated to the following Python code:
req.write("""<html> """) for n in range(3): # This indent will persist req.write(""" <p>This paragraph will be repeated 3 times.</p> """) # This line will cause the block to end req.write(""" This line will only be shown once.<br> </html> """)
The parser is also smart enough to figure out the indent if the last line of Python ends with ":" (colon). Considering this, and that the indent is reset when a newline is encountered inside "<% %>", the above page can be written as:
<html> <% for n in range(3): %> <p>This paragraph will be repeated 3 times.</p> <% %> This line will only be shown once.<br> </html>
However, the above code can be confusing, thus having descriptive comments denoting blocks is highly recommended as a good practice.
The only directive supported at this time is include
, here is
how it can be used:
<%@ include file="/file/to/include"%>
If the parse() function was called with the dir argument, then the file can be specified as a relative path, otherwise it has to be absolute.