Search code examples
pythonhtmlcssweasyprint

Combining head, body and footer in HTML (or with CSS?)


I have two separate files called head.html and footer.html, each of which has several formatting options. In a python script, I am processing some text for the body:

sometext=inspect.cleandoc(f'''
  <body>
  This is some text.
  </body>
''')
Html_file= open('path/to/my/output.html',"w")
Html_file.write(sometext)
Html_file.close()

How do I:

  1. Include the head.html and footer.html in my output.html in python, with the body in the middle? I was thinking, perhaps I can open head.html > write to output.html, open this file with open( ... , 'a') > write the footer. But perhaps there is a better way?
  2. I am a bit confused as to how to use the CSS together with the html and my text generated in python. I understand how to write each of these, but not really sure how to get them to work together.

My goal is to use the head.html, body, footer.html in a single html file, and then convert it to PDF using weasyprint.


Solution

  • This script should do what you describe:

    # open output file
    Html_file= open('path/to/my/output.html',"w")
    
    # write from header file to output file
    with open('path/to/my/header.html') as header_file:
        for line in header_file:
            Html_file.write(line)
    
    # write body
    sometext=inspect.cleandoc(f'''
      <body>
      This is some text.
      </body>
    ''')
    Html_file.write(sometext)
    
    # write from footer file to output file
    with open('path/to/my/footer.html') as footer_file:
        for line in footer_file:
            Html_file.write(line)
    
    # close output file
    Html_file.close()