473,387 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

recommended way of generating HTML from Python

What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.

Michele Simionato

Jul 18 '05 #1
13 2361
Michele Simionato napisał(a):
What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.


I don't thing there is anything "recommended" except personal
recommendations. Personally, I like Hamish Sanderson's HTMLTemplate
(http://freespace.virgin.net/hamish.s...template.html), but I
may be biased. ;)

Hamish planned to start process that would lead to inclusion of
HTMLTemplate to standard library, but I don't think it's gonna happen in
any foreseeable future.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
Jul 18 '05 #2
Just to clarify, before people start pointing out their preferred
templating language: I am NOT asking for
a template system. I am asking for something on the
lines of HTMLGen, where you just use pure Python.

Jul 18 '05 #3
Michele Simionato wrote:
What is the recommended way of generating HTML from Python? I know of
HTMLGen and of
few recipes in the Cookbook, but is there something which is more or
less standard?
I'm also an htmlgen user, but it's getting a bit long in the tooth, and the
installation is not very clean (pre-distutils). I keep an eye out for
alternatives, here's one (which I haven't looked at yet):

######
htmldata 1.0.6 is available.

http://oregonstate.edu/~barnesc/htmldata/

The htmldata module allows one to translate HTML
documents back and forth to list data structures.
This allows for programmatic reading and writing
of HTML documents, with much flexibility.

######

I could swear that I also saw another recent email announcing an htmlgen
alternative, but no amount of googling or digging through my email could turn
it up. I think it was in the last month or so, and probably on the
python-announce list, but looking through the archives I can't find it. Maybe
my memory is playing tricks on me.
Also, are there plans to include a module for HTML generation in the
standard library?
I really would like to see some standardization in this area.


I would too. The HTMLgen model is quite nice and clean (at least for my simple
uses), but I'd use anything, as long as it's included by default and supported.

Cheers,

f

Jul 18 '05 #4
Here are a couple of pointers. I agree with Michele that it would be
nice to have some kind of standardization. Maybe this would be worth a
post to the Web-SIG ?

- I posted a 70-line recipe on the Python Cookbook, a sort of poor man's
HTMLGen called HTMLTags
http://aspn.activestate.com/ASPN/Coo.../Recipe/366000
with a syntax like this :

# print HTML( HEAD(TITLE('Test document')) +
# BODY(H1('This is a test document')+
# TEXT('First line')+BR()+
# TEXT('Second line')))

The use of addition allows for shortcuts like
print Sum([ TR(TD(i)+TD(i*i)) for i in range(100) ])

where Sum works like the built-in sum, but sum only works for numbers
apparently

- in the Cookbook someone mentioned the HyperText package, published in
2000 by Andy Dustman : http://dustman.net/andy/python/HyperText/

It uses this syntax :

# print TABLE(
# TR((TH('SPAM'), TH('EGGS')),
# TR(TD('foo','bar', colspan=2))
# )

The package also handles XML, SGML etc.

- I wrote to Andy and he said there was also Living Logic's XIST :
http://www.livinglogic.de/Python/xist/index.html

An example taken from the site :

#node = xsc.Frag(
# xml.XML10(),
# html.DocTypeXHTML10transitional(),
# html.html(
# html.head(
# meta.contenttype(),
# html.title("Example page")
# ),
# html.body(
# html.h1("Welcome to the example page"),
# html.p(
# "This example page has a link to the ",
# html.a("Python home page", href="http://www.python.org/"),
# "."
# )
# )
# )
# )
#
# print node.conv().asBytes(encoding="us-ascii")
Jul 18 '05 #5
Stan (part of nevow, which is part of twisted) is a nice python syntax
for building HTML - I like the use of () and [] to separate attributes
from sub-elements.

For example:

class Greeter(rend.Page):
def greet(self, context, data):
return random.choice(["Hello", "Greetings", "Hi"]), " ", data

docFactory = loaders.stan(
tags.html[
tags.head[ tags.title[ "Greetings!" ]],
tags.body[
tags.h1(style="font-size: large")[ "Now I will greet you:" ],
greet
]
])

(From http://nevow.com/releases/0.3.0/nevow-intro.html)

I don't know how detachable it is from the rest of nevow. I'd assume it
wouldn't be too difficult to implement in a standalone fashion.

xtian

Jul 18 '05 #6
has
xtian wrote:
Stan (part of nevow, which is part of twisted) is a nice python syntax for building HTML [...] I don't know how detachable it is from the rest of nevow. I'd assume it wouldn't be too difficult to implement in a standalone fashion.


FWIW I whipped up a simple self-contained Stan clone a while back:

http://freespace.virgin.net/hamish.s...on/stanlite.py

It's a bit quick-n-dirty - I think ideally you'd want it to parse all
the HTML element information from a DTD and perform proper validation
of input data - but if anyone want to pick it up and run with it, or
just use it as-is, they're more than welcome to.

HTH

has

Jul 18 '05 #7
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).

FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

..def makeattr(dict_or_list_of_pairs):
.. dic = dict(dict_or_list_of_pairs)
.. return " ".join("%s=%r" % (k, dic[k]) for k in dic)

..class HTMLTag(object):
.. def __getattr__(self, name):
.. def tag(value, **attr):
.. """value can be a string or a sequence of strings."""
.. if hasattr(value, "__iter__"): # is iterable
.. value = " ".join(value)
.. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
.. return tag

# example:
..html = HTMLTag()

..tableheader = ["field1", "field2"]
..tablebody = [["a1", "a2"],
.. ["b1", "b2"]]

..html_header = [html.tr(html.th(el) for el in tableheader)]
..html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
..print html.table(html_header + html_table)

Michele Simionato

Jul 18 '05 #8
Michele Simionato wrote:
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
Why not teach your students to use a template system?
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

.def makeattr(dict_or_list_of_pairs):
. dic = dict(dict_or_list_of_pairs)
. return " ".join("%s=%r" % (k, dic[k]) for k in dic)

.class HTMLTag(object):
. def __getattr__(self, name):
. def tag(value, **attr):
. """value can be a string or a sequence of strings."""
. if hasattr(value, "__iter__"): # is iterable
. value = " ".join(value)
. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
. return tag

# example:
.html = HTMLTag()

.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]

.html_header = [html.tr(html.th(el) for el in tableheader)]
.html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
.print html.table(html_header + html_table)
*Shudder*

I've written web pages this way (using a pretty nice Java HTML generation package) and I don't
recommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to code and back is
difficult.
- It is hard to work with a designer. The designer will give you sample web pages which then have to
be hand-translated to code. Changes to the web page have to be located in the code.
- There is no separation of content and presentation

IMO templating systems are a much better solution. They let you express HTML in HTML directly; you
communicate with a designer in a language the designer understands; you can separate content and
presentation.

Kent

Michele Simionato

Jul 18 '05 #9
On Mon, 2005-02-21 at 07:36 -0500, Kent Johnson wrote:
Michele Simionato wrote:
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
Why not teach your students to use a template system?
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

.def makeattr(dict_or_list_of_pairs):
. dic = dict(dict_or_list_of_pairs)
. return " ".join("%s=%r" % (k, dic[k]) for k in dic)

.class HTMLTag(object):
. def __getattr__(self, name):
. def tag(value, **attr):
. """value can be a string or a sequence of strings."""
. if hasattr(value, "__iter__"): # is iterable
. value = " ".join(value)
. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
. return tag

# example:
.html = HTMLTag()

.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]

.html_header = [html.tr(html.th(el) for el in tableheader)]
.html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
.print html.table(html_header + html_table)


*Shudder*

I've written web pages this way (using a pretty nice Java HTML generation package) and I don't
recommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to code and back is
difficult.
- It is hard to work with a designer. The designer will give you sample web pages which then have to
be hand-translated to code. Changes to the web page have to be located in the code.
- There is no separation of content and presentation


Slightly off topic but, just to be clear, Nevow supports XHTML templates
*and* stan tag expressions. Both are useful. As a general rule, I stick
to XHTML templates but I use stan for prototyping pages and when marking
up the XHTML templates gets so complicated that they might as well be
written in Python anyway.

Also, just because the HTML code is not in a .html file does not
necessarily mean that content and presentation are mixed up. For
instance, with stan (and probably the alternatives mentioned in this
thread) it's very easy to build a tag library that the "real" Python
code simply calls on to render page content.

IMO templating systems are a much better solution. They let you express HTML in HTML directly; you
communicate with a designer in a language the designer understands; you can separate content and
presentation.


Agreed. Although I would go further and say that it's important to
choose a templating system that allows the Python developer to annotate
XHTML templates using **valid XML**, i.e. no "for x in y" loops, no "if
foo" conditionals, no "i = 0" variable setting, no expression
evaluations, etc.
<advocacy>
The lovely thing about Nevow is that it encourages good separation -
HTML is HTML and logic is Python, as it should be - but does not get in
the way when breaking the rules is necessary or just a lot easier.
</advocacy>
Cheers, Matt

--
__
/ \__ Matt Goodall, Pollenation Internet Ltd
\__/ \ w: http://www.pollenation.net
__/ \__/ e: ma**@pollenation.net
/ \__/ \ t: +44 (0)113 2252500
\__/ \__/
/ \ Any views expressed are my own and do not necessarily
\__/ reflect the views of my employer.

Jul 18 '05 #10
Kent Johnson:
I've written web pages this way (using a pretty nice Java HTML generation package) >and I don'trecommend it. In my experience, this approach has several drawbacks:
- as soon as the web page gets at all complex, the conceptual shift from HTML to >code and back isdifficult.
- It is hard to work with a designer. The designer will give you sample web pages >which then have tobe hand-translated to code. Changes to the web page have to be located in the code.- There is no separation of content and presentation IMO templating systems are a much better solution. They let you express HTML in >HTML directly; youcommunicate with a designer in a language the designer understands; you can >separate content andpresentation


You make a series of good points I am well aware of; however, still
there are
places were direct HTML generation can be a reasonable approach (my use
case was the formatting of a SQL query): cases where the result will
never
ever touch a designer. Also, one could argue that the designer should
not
get in touch with the HTML, but just play with the CSS.
Finally, you can achieve separation between logic and presentation just
putting the
routines generating the HTML pages in a separate module, no need to use
a
different language.

Michele Simionato

Jul 18 '05 #11
has
Kent Johnson wrote:
Michele Simionato wrote:
The problem is a problem of standardization, indeed. There plenty of recipes to
do the same job, I just would like to use a blessed one (I am teaching a Python
course and I do not know what to recommend to my students).


Why not teach your students to use a template system?


Agreed. Don't use HTML generation simply for the sake of it. While it
has its niche, for most tasks templating is more appropriate. There
aren't any 'blessed' solutions, so just pick whichever third-party
system best fits your needs.

Jul 18 '05 #12
Matt Goodall <ma**@pollenation.net> writes:
[...]
Agreed. Although I would go further and say that it's important to
choose a templating system that allows the Python developer to annotate
XHTML templates using **valid XML**, i.e. no "for x in y" loops, no "if
foo" conditionals, no "i = 0" variable setting, no expression
evaluations, etc.

[...]

Why does use of a templating system whose documemts are valid XML
imply no loops, conditionals, expression evaluation etc.?

Or are you just talking about particular (non-XML) syntaxes for these
constructs?
John
Jul 18 '05 #13
Michele Simionato wrote:
Also, one could argue that the designer should
not get in touch with the HTML, but just play with the CSS.
Finally, you can achieve separation between logic and presentation just
putting the routines generating the HTML pages in a separate module, no need to use
a different language.


Yea, why can't we start using xHTML like any other GUI toolkit, its just
a tree of widgets. The layout is completely up to CSS... One could write
Form classes with automatic generation of client(javascript) and
server side(python) validators ;)

greetings
Paul
Jul 18 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Dan Gass | last post by:
The difflib.py module and the diff.py tools script in Python 2.4 alpha 3 now support generating side by side (with intra line differences) in HTML format. I have found this useful for performing...
8
by: Tim Daneliuk | last post by:
I use a makefile to create distribution tarballs of freestanding Python programs and their documentation. I cannot seem to find the right command line option to just generate a pyc/pyo file from...
0
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
4
by: Andreas Jung | last post by:
Hi, does anyone know of a high-level solution to produce RTF from Python (something similar to Reportlab for producing PDF)? Thanks, Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG...
17
by: flupke | last post by:
Hi, i create my GUIs mainly via wxGlade. However when you start of to program and want to do some rearranging to the gui, wxglade overwrites your file and you've got to put your own code back...
14
by: Philippe C. Martin | last post by:
Hi, I wish to use an easy way to generate reports from wxPython and feel wxHtmlEasyPrinting could be a good solution. I now need to generate the HTML wxHtmlEasyPrinting can print: I need to...
6
by: John Machin | last post by:
Hi, In general, I'm mainly interested in a template engine for dynamic web pages but would like a general purpose one to avoid learning yet another package for generating e-mail messages, form...
4
by: John Nagle | last post by:
What's the recommended FastCGI module for Python. There are at least five: The Robin Dunn / Total Control Software version: http://alldunn.com/python/fcgi.py Last revised in 1998. The...
3
by: Ge Chunyuan | last post by:
hi Group: I am a new comer for Python, I wonder which IDE is recommended in Windows OS. Can anyone give some suggestion. Thanks indeed Ge Chunyuan
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.