|
# |
|
# Simple Inline X/HTML Generator |
|
# by Toni Mattis |
|
# |
|
''' |
|
Example usage: |
|
|
|
from tags import * |
|
print div(cls = 'myclass')[ p['Hello'], hr, p[strong['World']] ] |
|
|
|
''' |
|
|
|
REPLACE = { |
|
'cls': 'class' |
|
} |
|
|
|
class Tag(object): |
|
|
|
def __init__(self, name, **attrs): |
|
self._name = name |
|
self._attrs = attrs |
|
self._subtags = [] |
|
|
|
def _gettag(self, name): |
|
return Tag(name) |
|
|
|
def __str__(self): |
|
attr_str = (' ' + ' '.join( |
|
['%s="%s"' % (k, v) for k, v in self._attrs.items()])) \ |
|
if self._attrs else '' |
|
if self._subtags: |
|
return '<%s%s>' % (self._name, attr_str) \ |
|
+ ''.join(map(str, self._subtags)) \ |
|
+ '</%s>' % self._name |
|
else: |
|
return '<%s%s />' % (self._name, attr_str) |
|
|
|
def __call__(self, **kwargs): |
|
attrs = {(REPLACE[k] if k in REPLACE else k) : v |
|
for k, v in kwargs.items()} |
|
t = Tag(self._name, **attrs) |
|
t._subtags = self._subtags |
|
return t |
|
|
|
def __getitem__(self, args): |
|
t = Tag(self._name, **self._attrs) |
|
if isinstance(args, tuple) or isinstance(args, list): |
|
t._subtags = args |
|
else: |
|
t._subtags = [args] |
|
return t |
|
|
|
__repr__ = __str__ |
|
|
|
TAGS = ( |
|
'html', 'head', 'title', 'body', 'link', 'meta', 'script', 'style', 'base', |
|
'noscript', |
|
'section', 'nav', 'article', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', |
|
'header', 'footer', 'address', 'main', |
|
'div', 'p', 'br', 'hr', 'pre', 'blockquote', |
|
'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'figure', 'figcaption', |
|
'table', 'td', 'th', 'tr', 'thead', 'tbody', 'tfoot', 'col', 'caption', 'colgroup', |
|
'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'code', 'var', 'samp', 'sub', 'sup', |
|
'i', 'b', 'u', |
|
'span', |
|
'img', 'param', 'video', 'audio', 'svg', 'area', |
|
'form', 'fieldset', 'legend', 'label', 'input', 'button', 'select', |
|
'optgroup', 'option', 'textarea', 'output', 'progress', 'meter', |
|
) |
|
|
|
for tag in TAGS: |
|
globals()[tag] = Tag(tag) |
I have something like this here but for the command line: