Generating HTML documents in python

前端 未结 7 1135
花落未央
花落未央 2020-11-28 03:43

In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a mor

相关标签:
7条回答
  • 2020-11-28 04:29

    There is also a nice, modern alternative: airium: https://pypi.org/project/airium/

    from airium import Airium
    
    a = Airium()
    
    a('<!DOCTYPE html>')
    with a.html(lang="pl"):
        with a.head():
            a.meta(charset="utf-8")
            a.title(_t="Airium example")
    
        with a.body():
            with a.h3(id="id23409231", klass='main_header'):
                a("Hello World.")
    
    html = str(a) # casting to string extracts the value
    
    print(html)
    

    Prints such a string:

    <!DOCTYPE html>
    <html lang="pl">
      <head>
        <meta charset="utf-8" />
        <title>Airium example</title>
      </head>
      <body>
        <h3 id="id23409231" class="main_header">
          Hello World.
        </h3>
      </body>
    </html>
    

    The greatest advantage of airium is - it has also a reverse translator, that builds python code out of html string. If you wonder how to implement given html snippet - the translator gives you the answer right away.

    E.g. its tests contain example pages translated automatically with airium: https://gitlab.com/kamichal/airium/-/tree/master/tests/documents

    0 讨论(0)
提交回复
热议问题