update_layout.py 1.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#!/usr/bin/env python
import os


def main():
    """Update the HTML files based on the _layout.html file."""
    LAYOUT_KEYWORD = "<!--yield-->"  # Placeholder text in the layout HTML file.
    OUTPUT_KEYWORD = "<!--content-->"  # Layout "boundaries" in the output HTML.

    # Read in the "layout" HTML. This is used as a template for the other files.
    with open("_layout.html") as layout_file:
        layout_html = layout_file.read()

    # Update the contents of the other HTML files to match the "layout" HTML.
    for file_name in os.listdir("."):
        if file_name.startswith("_") or not file_name.lower().endswith(".html"):
            continue  # Ignore non-HTML files and the layout HTML.

        print(" ".join(["Updating", file_name]))
        with open(file_name) as src:
            # Get the current HTML content and remove any old "layout" stuff.
            old_content = src.read().split(OUTPUT_KEYWORD)
            if len(old_content) == 3:
                text = old_content[1]  # Parts 0 and 2 are the old layout HTML.
            elif len(old_content) == 1:
                text = old_content[0]  # No layout HTML keywords were found.
            else:
                print(' '.join(["\tCouldn't update", file_name]))
                continue  # The number of marker keywords doesn't make sense...

            # Wrap the page content in the NEW layout HTML and overwrite it.
            text = '\n'.join([OUTPUT_KEYWORD, text.strip(), OUTPUT_KEYWORD])
            with open(file_name, 'w') as out:
                out.write(layout_html.replace(LAYOUT_KEYWORD, text))

if __name__ == '__main__':
    main()