Python embedded like PHP
Dave Cole
djc at object-craft.com.au
Wed Mar 13 07:16:59 EST 2002
> >Are there any projects out there that allow you to embed python in
> >HTML like PHP? I like the PHP-style of embedding the bits of
> >program in HTML, but I'd like to use python... Something like:
> >
> ><html>
> ><?python
> > print "<ul>"
> > for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]:
> > print "<li> %s </li>" % reptile
> > print "</ul>"
> >?>
> ></html>
The example Andrew presented is certainly the Albatross way, but you
could also do things like this with Andrew's improved template parser
in 0.06 (if you were so inclined):
- - reptile.html - - - - - - - - - - - - - - - - - - - - - - - - - -
<html>
<al-exec expr='
print "<ul>"
for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]:
print "<li> %s </li>" % reptile
print "</ul>"
'>
</html>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The example program adds a write() method to the execution context to
make it look like a file for the print statement.
- - reptile.py - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/python
import sys
import albatross
class Ctx(albatross.SimpleContext):
def write(self, data):
self.write_content(data)
ctx = Ctx('.')
ctx.locals.reptiles = ["Crocodile", "Python", "Iguana", "Tortoise"]
template = ctx.load_template("reptiles.html")
old_stdout = sys.stdout
try:
sys.stdout = ctx
template.to_html(ctx)
finally:
sys.stdout = old_stdout
print "Content-Type: text/html"
print
ctx.flush_content()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Produces the following output...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content-Type: text/html
<html>
<ul>
<li> Crocodile </li>
<li> Python </li>
<li> Iguana </li>
<li> Tortoise </li>
</ul>
</html>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Dave
--
http://www.object-craft.com.au
More information about the Python-list
mailing list