Skip to content

Instantly share code, notes, and snippets.

@iomarmochtar
Created July 4, 2019 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iomarmochtar/78fceabbfe17c032b8a8b31e6bb03151 to your computer and use it in GitHub Desktop.
Save iomarmochtar/78fceabbfe17c032b8a8b31e6bb03151 to your computer and use it in GitHub Desktop.
a python library to generating xml tag
__author__ = ('Imam Omar Mochar', ('iomarmochtar@gmail.com',))
"""
Simple XML builder, i create it for generating HTML tag(s)
"""
# alternative of xml attribute that also become keyword in python side
ALTERNATE_MAP = {
'klass': 'class'
}
class Tag(object):
name = None
def __init__(self, name):
self.name = name
def __call__(self, *contents, **attrs):
h_attrs = []
for k,v in attrs.items():
if k in ALTERNATE_MAP:
k = ALTERNATE_MAP[k]
h_attrs.append('{}="{}"'.format(k,v))
return '<{tagname}{h_attrs}>{contents}</{tagname}>'.format(
tagname=self.name,
contents=' '.join(contents) if contents else '',
h_attrs=' {}'.format(' '.join(h_attrs)) if h_attrs else ''
)
class IntheMiddle(object):
"""
Bridging to Tag class
"""
def __getattribute__(self, name):
node = Tag(name)
return node
SimpleTag = IntheMiddle()
@iomarmochtar
Copy link
Author

Example for using this library, some attribute will be renamed for the list of it you can see ALTERNATE_MAP (because some has been taken as python keyword)

from simpletag import SimpleTag as T

rows = []
for x in range(10):
    rows.append(T.tr(
                    T.td('Col1'),
                    T.td('Col2')
                    ,scope='row'
                ))

tbody = T.tbody(*rows)
table = T.table(tbody, klass='table table-striped', style='margin-elft: 1;')
print(table)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment