How do web templates separate content and logic?

Kirk Strauser kirk at daycos.com
Tue Jul 1 17:24:00 CEST 2008


At 2008-06-30T19:34:53Z, Mike <termim at gmail.com> writes:

> I should have say "why embedding HTML into Python is not good enough?" ;=)

I'm a programmer and would be able to cope with embedding HTML in assembler
if the need arose.

Having said that, embedding HTML in anything but HTML tends to be a bad idea
in the long run.  Inevitably, you're going to want to move stuff around, and
find out that you can't just move

    print "<ul>"
    for item in itemlist:
        print "<li>%s</li>" % item
    print "</ul>"

up near the top because you don't actually define itemlist until near the
end of your function, because it's built on the results of a bunch of other
code.

So then you "solve" the problem by leaving that snippet where it is and
moving all the other HTML print commands after it.  Oh, crud!  You realize
too late that some of your print commands have side effects:

    for item in deletelist:
        print "<p>Deleting %s: %s</p>" % (str(item), mangle(item))

and if you run that code *after* you generate itemlist, the results will be
all screwed up.

So you go back and move all of your logic to the top of the function and all
of the HTML print statements to the bottom.  And then you realize you've
written your very own page template, and that it's ugly, and that you
should've used something different from the very beginning.

That's why you don't embed HTML in Python, at least not for anything more
complicated than "Hello, world".
-- 
Kirk Strauser
The Day Companies



More information about the Python-list mailing list