summaryrefslogtreecommitdiff
path: root/bs4/element.py
diff options
context:
space:
mode:
authorLeonard Richardson <leonardr@segfault.org>2019-07-07 22:57:04 -0400
committerLeonard Richardson <leonardr@segfault.org>2019-07-07 22:57:04 -0400
commit519afbe269b671e15a1f1d2aecfe4fc579b61efc (patch)
tree34009e19c95cae9245678451f3d7dc783f75f59a /bs4/element.py
parent2fcaeb6e916a09fa87b4b2ab57167c39db6cef8c (diff)
A Formatter can now decide how (or whether) to order the attributes
inside a tag. [bug=1812422]
Diffstat (limited to 'bs4/element.py')
-rw-r--r--bs4/element.py15
1 files changed, 12 insertions, 3 deletions
diff --git a/bs4/element.py b/bs4/element.py
index 1183f77..e8e48df 100644
--- a/bs4/element.py
+++ b/bs4/element.py
@@ -142,15 +142,20 @@ class Formatter(object):
# By default, represent void elements as <tag/> rather than <tag>
void_element_close_prefix = '/'
- def substitute_entities(self, *args, **kwargs):
+ def substitute(self, *args, **kwargs):
"""Transform certain characters into named entities."""
raise NotImplementedError()
+
+ def sort_attributes(self, attributes):
+ """Reorder a tag's attributes however you want."""
+ return sorted(attributes.items())
+
class HTMLFormatter(Formatter):
"""The default HTML formatter."""
def substitute(self, *args, **kwargs):
return HTMLAwareEntitySubstitution.substitute_html(*args, **kwargs)
-
+
class MinimalHTMLFormatter(Formatter):
"""A minimal HTML formatter."""
def substitute(self, *args, **kwargs):
@@ -1157,7 +1162,11 @@ class Tag(PageElement):
formatter = self._formatter_for_name(formatter)
attrs = []
if self.attrs:
- for key, val in sorted(self.attrs.items()):
+ if isinstance(formatter, Formatter):
+ sorted_attrs = formatter.sort_attributes(self.attrs)
+ else:
+ sorted_attrs = self.attrs.items()
+ for key, val in sorted_attrs:
if val is None:
decoded = key
else: