Skip to content

Instantly share code, notes, and snippets.

@MattMS MattMS/h.py
Created May 12, 2019

Embed
What would you like to do?
Create HTML with Python
def _add_global(name, value):
globals()[name] = value
def _replace_underscore(text):
return text.replace('_', '-')
class h:
def __init__(self, *children, **attributes):
self.attributes = attributes
self.children = children
def __str__(self):
a_parts = ['{0}="{1}"'.format(_replace_underscore(k), v) for k, v in self.attributes.items()]
a = ' {}'.format(' '.join(a_parts)) if len(a_parts) > 0 else ''
if len(self.children) > 0:
return '<{tag}{attributes}>{children}</{tag}>'.format(
attributes=a,
children=''.join(map(str, self.children)),
tag=self.tag
)
else:
return '<{tag}{attributes} />'.format(
attributes=a,
tag=self.tag
)
def set_tag(t):
def modifier(element_class):
class tagged(element_class):
tag = t
return tagged
return modifier
for i in range(6):
tag = 'h{}'.format(i)
_add_global(tag, set_tag(tag)(h))
for tag in ['a', 'body', 'div', 'head', 'meta', 'p', 'title']:
_add_global(tag, set_tag(tag)(h))
# a = set_tag('a')(h)
# @set_tag('div')
# class div(h):
# pass
def charset(name='utf-8'):
return meta(charset=name)
class html(h):
doctype = '<!doctype html>'
tag = 'html'
def __str__(self):
return '\n'.join([
self.doctype,
h.__str__(self)
])
print(
html(
head(
charset(),
title('My page', id='title')
),
body(
h1(a('Hello', id='link')),
p('It works', data_field='value')
)
)
)
# =
# <!doctype html>
# <html><head><meta charset="utf-8" /><title id="title">My page</title></head><body><h1><a id="link">Hello</a></h1><p data-field="value">It works</p></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.