By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,885 Members | 1,499 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,885 IT Pros & Developers. It's quick & easy.

recommended way of generating HTML from Python

P: n/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.

Michele Simionato

Jul 18 '05 #1
Share this Question
Share on Google+
13 Replies


P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.