Skip to content

Instantly share code, notes, and snippets.

@fevral13
Last active February 11, 2019 04:26
Show Gist options
  • Select an option

  • Save fevral13/d2cdb56c5bc2ba77b2b9c2dd157e1689 to your computer and use it in GitHub Desktop.

Select an option

Save fevral13/d2cdb56c5bc2ba77b2b9c2dd157e1689 to your computer and use it in GitHub Desktop.
hiccup template engine naive Python implementation
class StringMeta(type):
def __getattr__(cls, name):
return name
class e(metaclass=StringMeta):
pass
def render_attrs(attrs):
return ' '.join(('{}="{}"'.format(key, value) for key, value in attrs.items()))
def render_element(elem, attrs, subtree=[]):
subelements = [render_element(*_subelement) for _subelement in subtree]
rendered_subtree = '\n'.join(subelements)
attributes = render_attrs(attrs)
return '<{elem} {attrs}>\n{subtree}</{elem}>\n'.format(
elem=elem,
attrs=attributes,
subtree=rendered_subtree
)
def hiccup(tree):
return render_element(*tree)
form = [e.form, {'method': 'post', 'action': ''}, [
[e.input, {'name': 'email', 'type': 'text', 'value': ''}],
[e.input, {'name': 'password', 'type': 'password', 'value': ''}],
[e.input, {'type': 'submit', 'value': 'Enter'}],
]]
page = [e.html, {}, [
[e.head, {}],
[e.body, {'class': 'body'}, [form]]
]
]
print(hiccup(page))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment