Skip to content

Instantly share code, notes, and snippets.

@samdbmg
Created June 11, 2014 00:54
Show Gist options
  • Save samdbmg/b3efefbd09d8e108cc6b to your computer and use it in GitHub Desktop.
Save samdbmg/b3efefbd09d8e108cc6b to your computer and use it in GitHub Desktop.
A simple HTML templating system - wraps a template file (such as a menu) around a named div containing content.
import os
import sys
from bs4 import BeautifulSoup
"""Bogotemplater template engine
Wraps a specified element in every HTML file in target directory with a template file
"""
DIRECTORY = "TargetSite"
TEMPLATE = "template.html"
ELEMENT = "right"
def main():
print "BogoTemplater - The crappy HTML template engine"
print "Now searching " + DIRECTORY
# Get list of html/htm files in target directory
matches = []
for root, dirs, files in os.walk(DIRECTORY):
for filename in files:
if filename.endswith(('.htm', '.html')):
matches.append(os.path.join(root, filename))
print "Found " + str(len(matches)) + " files to play with"
for filename in matches:
#filename = matches[1]
#for i in range(0,1):
print "\nNow loading " + filename
contentfile = BeautifulSoup(open(filename))
contentdiv = contentfile.find(id=ELEMENT)
oldtitle = contentfile.title
newfile = BeautifulSoup(open(TEMPLATE))
urltop = os.path.relpath(DIRECTORY, filename).replace('\\', '/').lstrip("..").lstrip("/")
if urltop.startswith(".."):
urltop = urltop + "/"
else:
urltop = ""
try:
# Replace all relative paths with new tree size
for urlgroup in newfile.find_all('a'):
urlgroup['href'] = urltop + urlgroup['href']
for urlgroup in newfile.find_all('link'):
urlgroup['href'] = urltop + urlgroup['href']
for urlgroup in newfile.find_all(src=True):
urlgroup['src'] = urltop + urlgroup['src']
# Replace template data bits
newfile.find(id=ELEMENT).replace_with(contentdiv)
newfile.title.replace_with(oldtitle)
resultinghtml = newfile.prettify(formatter="html")
f = open(filename, 'w')
f.write(resultinghtml)
f.close()
except AttributeError:
print "File " + filename + " doesn't have an " + ELEMENT + " element"
if __name__ == '__main__':
main()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment