Craft Beetle
HEADER AND FOOTER UPDATING
All my web pages have a header and footer demarcated by the comments:
'<!-- header start -->'
'<!-- header end -->'
'<!-- footer start -->'
'<!-- footer end -->'
Running the script below automatically goes through each webpage and replaces the header and footer with
the contents of these files:
"header_template.html"
"footer_template.html"
import os
# Get the directory of the current script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Define the paths to the template files
header_template_path = os.path.join(script_dir, 'header_template.html')
footer_template_path = os.path.join(script_dir, 'footer_template.html')
# Read the contents of the header and footer template files
with open(header_template_path, 'r') as header_file:
header_content = header_file.read()
with open(footer_template_path, 'r') as footer_file:
footer_content = footer_file.read()
# Function to replace header and footer in HTML files
def replace_header_footer(directory):
for root, dirs, files in os.walk(directory):
for file in files:
# Process only HTML files and exclude template files
if file.endswith('.html') and file not in [os.path.basename(header_template_path), os.path.basename(footer_template_path)]:
file_path = os.path.join(root, file)
with open(file_path, 'r') as html_file:
content = html_file.read()
# Replace header
content_parts = content.split('<!-- header end -->')
if len(content_parts) > 1:
content_parts[0] = header_content + '\n<!-- header end -->'
content = ''.join(content_parts)
# Replace footer
footer_start = '<!-- footer start -->'
footer_end = '<!-- footer end -->'
if footer_start in content and footer_end in content:
footer_section = content.split(footer_start, 1)
footer_section[1] = footer_start + '\n' + footer_content + '\n' + footer_end
content = footer_section[0] + ''.join(footer_section[1:])
# Write the modified content back to the file
with open(file_path, 'w') as html_file:
html_file.write(content)
# Call the function with the root directory (one folder up)
replace_header_footer('..')
ยฉ 2024-2026 Craft Beetle | All rights reserved