recommended way of generating HTML from Python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michele Simionato

    #1

    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

  • Jarek Zgoda

    #2
    Re: recommended way of generating HTML from Python

    Michele Simionato napisa³(a):
    [color=blue]
    > 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.[/color]

    I don't thing there is anything "recommende d" 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/

    Comment

    • Michele Simionato

      #3
      Re: recommended way of generating HTML from Python

      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.

      Comment

      • Fernando Perez

        #4
        Re: recommended way of generating HTML from Python

        Michele Simionato wrote:
        [color=blue]
        > 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?[/color]

        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.



        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.
        [color=blue]
        > 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.[/color]

        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

        Comment

        • Pierre Quentel

          #5
          Re: recommended way of generating HTML from Python

          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

          with a syntax like this :

          # print HTML( HEAD(TITLE('Tes t 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','ba r', colspan=2))
          # )

          The package also handles XML, SGML etc.

          - I wrote to Andy and he said there was also Living Logic's XIST :


          An example taken from the site :

          #node = xsc.Frag(
          # xml.XML10(),
          # html.DocTypeXHT ML10transitiona l(),
          # html.html(
          # html.head(
          # meta.contenttyp e(),
          # html.title("Exa mple page")
          # ),
          # html.body(
          # html.h1("Welcom e 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().asB ytes(encoding=" us-ascii")

          Comment

          • xtian

            #6
            Re: recommended way of generating HTML from Python

            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.Pa ge):
            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

            Comment

            • has

              #7
              Re: recommended way of generating HTML from Python

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

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



              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

              Comment

              • Michele Simionato

                #8
                Re: recommended way of generating HTML from Python

                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_o r_list_of_pairs ):
                .. dic = dict(dict_or_li st_of_pairs)
                .. return " ".join("%s= %r" % (k, dic[k]) for k in dic)

                ..class HTMLTag(object) :
                .. def __getattr__(sel f, name):
                .. def tag(value, **attr):
                .. """value can be a string or a sequence of strings."""
                .. if hasattr(value, "__iter__") : # is iterable
                .. value = " ".join(valu e)
                .. 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

                Comment

                • Kent Johnson

                  #9
                  Re: recommended way of generating HTML from Python

                  Michele Simionato wrote:[color=blue]
                  > 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).[/color]

                  Why not teach your students to use a template system?
                  [color=blue]
                  > FWIW, here is a my version of the recipe (stripped down to the bare
                  > essentials)
                  >
                  > .def makeattr(dict_o r_list_of_pairs ):
                  > . dic = dict(dict_or_li st_of_pairs)
                  > . return " ".join("%s= %r" % (k, dic[k]) for k in dic)
                  >
                  > .class HTMLTag(object) :
                  > . def __getattr__(sel f, name):
                  > . def tag(value, **attr):
                  > . """value can be a string or a sequence of strings."""
                  > . if hasattr(value, "__iter__") : # is iterable
                  > . value = " ".join(valu e)
                  > . 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)[/color]

                  *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
                  [color=blue]
                  >
                  > Michele Simionato
                  >[/color]

                  Comment

                  • Matt Goodall

                    #10
                    Re: recommended way of generating HTML from Python

                    On Mon, 2005-02-21 at 07:36 -0500, Kent Johnson wrote:[color=blue]
                    > Michele Simionato wrote:[color=green]
                    > > 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).[/color]
                    >
                    > Why not teach your students to use a template system?
                    >[color=green]
                    > > FWIW, here is a my version of the recipe (stripped down to the bare
                    > > essentials)
                    > >
                    > > .def makeattr(dict_o r_list_of_pairs ):
                    > > . dic = dict(dict_or_li st_of_pairs)
                    > > . return " ".join("%s= %r" % (k, dic[k]) for k in dic)
                    > >
                    > > .class HTMLTag(object) :
                    > > . def __getattr__(sel f, name):
                    > > . def tag(value, **attr):
                    > > . """value can be a string or a sequence of strings."""
                    > > . if hasattr(value, "__iter__") : # is iterable
                    > > . value = " ".join(valu e)
                    > > . 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)[/color]
                    >
                    > *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[/color]

                    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.
                    [color=blue]
                    >
                    > 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.[/color]

                    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: matt@pollenatio n.net
                    / \__/ \ t: +44 (0)113 2252500
                    \__/ \__/
                    / \ Any views expressed are my own and do not necessarily
                    \__/ reflect the views of my employer.

                    Comment

                    • Michele Simionato

                      #11
                      Re: recommended way of generating HTML from Python

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

                      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

                      Comment

                      • has

                        #12
                        Re: recommended way of generating HTML from Python

                        Kent Johnson wrote:[color=blue]
                        > Michele Simionato wrote:[color=green]
                        > > The problem is a problem of standardization , indeed. There plenty[/color][/color]
                        of[color=blue][color=green]
                        > > recipes to
                        > > do the same job, I just would like to use a blessed one (I am[/color][/color]
                        teaching[color=blue][color=green]
                        > > a Python
                        > > course and I do not know what to recommend to my students).[/color]
                        >
                        > Why not teach your students to use a template system?[/color]

                        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.

                        Comment

                        • John J. Lee

                          #13
                          Re: recommended way of generating HTML from Python

                          Matt Goodall <matt@pollenati on.net> writes:
                          [...][color=blue]
                          > 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.[/color]
                          [...]

                          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

                          Comment

                          • paul koelle

                            #14
                            Re: recommended way of generating HTML from Python

                            Michele Simionato wrote:[color=blue]
                            > 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.[/color]

                            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(javascri pt) and
                            server side(python) validators ;)

                            greetings
                            Paul

                            Comment

                            Working...