Last active
August 29, 2015 13:56
-
-
Save DrPaulBrewer/9104465 to your computer and use it in GitHub Desktop.
splitTemplates templates.html dirname -- refactoring tool to split out each <template name="xxx">contents</template> to its own file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Copyright 2014 Dr Paul Brewer -- Economic and Financial Technology Consulting LLC | |
# This script is made available under the terms of the MIT LICENSE | |
# Intended as a helper for refactoring template-enhanced html | |
# warning: overwrites existing files. | |
# Does not delete or modify original file templates.html | |
# Thanks to Stack Overflow users for these helpful hints: | |
# use of htmlparser to unescape entities | |
# http://stackoverflow.com/a/21894821/103081 | |
# http://stackoverflow.com/a/663128/103081 | |
# Requires Python module: beautiful soup "bs4" | |
# This module can be installed at either the system or user level | |
# at the system level, see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup | |
# if you aren't root, install bs4 at the user level, for example on a nitrous.io developer account: pip install --user bs4 | |
import bs4 | |
import sys | |
import os | |
import HTMLParser | |
U = HTMLParser.HTMLParser().unescape | |
if len(sys.argv) != 3: | |
print "usage: splitTemplates templates.html dirname" | |
print "for each <template name='xxx'> in templates.html creates a file xxx.html in dirname" | |
sys.exit(0) | |
filename = sys.argv[1] | |
fname, ext = os.path.splitext(filename) | |
dirname = sys.argv[2] | |
# make the directory dirname. If this fails, we assume it is because it existed already | |
try: | |
os.mkdir(dirname) | |
except OSError: | |
pass | |
soup = bs4.BeautifulSoup(open(filename,"r")) | |
for t in soup.children: | |
if t.name=="template": | |
newfname = dirname+"/"+t["name"]+ext | |
f = open(newfname,"w") | |
f.write(U(t.prettify(formatter=None))) | |
f.close() | |
print newfname | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment