Skip to content

Instantly share code, notes, and snippets.

@jdan
Created May 31, 2012 04:46
Show Gist options
  • Save jdan/2841106 to your computer and use it in GitHub Desktop.
Save jdan/2841106 to your computer and use it in GitHub Desktop.
ZenCoding clone
#!/usr/bin/python
# Zen-Coding clone by Jordan Scales - http://jscal.es
# 5/30/12
# reference: http://whiletruecode.com/post/stop-hand-coding-start-zen-coding
# div>ul>li*5
# expands to
# <div>
# <ul>
# <li></li>
# <li></li>
# <li></li>
# <li></li>
# <li></li>
# </ul>
# </div>
class HTMLNode:
def __init__(self, name, cl=None, children=[]):
self.name = name
self.cl = cl # class
self.children = children
def to_string(self, indent=0):
ret = ' ' * indent + '<%s' % self.name
# if there's a class
if self.cl:
ret += ' class="%s"' % self.cl
ret += '>'
# if we have no children, don't print a newline
# example: <li></li>
# otherwise, print all the children with a bigger indent
if len(self.children):
ret += '\n'
for child in self.children:
ret += child.to_string(indent+1)
ret += ' ' * indent
# print the end tag
ret += '</%s>\n' % self.name
return ret
def parse(string):
# recursive base case, we need to return an empty array
if not len(string):
return []
levels = string.split('>')
# dealing with multipliers
multiplier = 1
if levels[0].find('*') > -1:
tag_name, multiplier = levels[0].split('*')
else:
tag_name = levels[0]
# extracting the class
cl = None
if tag_name.find('.') > -1:
tag_name, cl = tag_name.split('.')
# building a return array
# that we can place as children, or fetch the first element of the root
ret = []
for i in range(int(multiplier)):
n = HTMLNode(tag_name, cl)
n.children = parse('>'.join(levels[1:]))
ret.append(n)
return ret
from sys import argv
def main():
if len(argv) > 1:
my_input = argv[1]
else:
my_input = raw_input('Shorthand: ')
# parse returns an array
# print each element, chopping off the trailing newline
p = parse(my_input)
for item in p:
print item.to_string()[:-1]
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment