Generating HTML documents in python

前端 未结 7 1185
花落未央
花落未央 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:22

    I would suggest using one of the many template languages available for python, for example the one built into Django (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template implementations.

    I find that learning a template library helps in so many ways - whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.

    Here's some simple code to get you started:

    #!/usr/bin/env python
    
    from django.template import Template, Context
    from django.conf import settings
    settings.configure() # We have to do this to use django templates standalone - see
    # http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
    
    # Our template. Could just as easily be stored in a separate file
    template = """
    
    
    Template {{ title }}
    
    
    Body with {{ mystring }}.
    
    
    """
    
    t = Template(template)
    c = Context({"title": "title from code",
                 "mystring":"string from code"})
    print t.render(c)
    

    It's even simpler if you have templates on disk - check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string - all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)

提交回复
热议问题