Created
July 4, 2019 07:18
-
-
Save iomarmochtar/78fceabbfe17c032b8a8b31e6bb03151 to your computer and use it in GitHub Desktop.
a python library to generating xml tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = ('Imam Omar Mochar', ('[email protected]',)) | |
""" | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)