From 1b73e1f4ee0bb6a3d9d8f8be59a562712412ace8 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 5 Feb 2023 14:49:09 +0200 Subject: [PATCH 1/2] Python 3.7 compat --- html5tagger/builder.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/html5tagger/builder.py b/html5tagger/builder.py index 7180b06..93ab010 100644 --- a/html5tagger/builder.py +++ b/html5tagger/builder.py @@ -1,5 +1,5 @@ from .html5 import omit_endtag -from .util import mangle, escape, escape_special, esc_script, esc_style, attributes +from .util import attributes, esc_script, esc_style, escape, escape_special, mangle class Builder: @@ -23,7 +23,11 @@ def _clear(self): @property def _allpieces(self): - return *self._pieces, self._endtag, *self._stack[::-1] + retval = [] + retval.extend(self._pieces) + retval.append(self._endtag) + retval.extend(self._stack[::-1]) + return tuple(retval) def _endtag_close(self): if self._endtag: From b9581c3a4a6a965a0a91b3b71800096b8855fe60 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 27 Aug 2023 09:01:25 +0300 Subject: [PATCH 2/2] Add CSS style attribute assignment --- html5tagger/builder.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/html5tagger/builder.py b/html5tagger/builder.py index 93ab010..0167059 100644 --- a/html5tagger/builder.py +++ b/html5tagger/builder.py @@ -1,7 +1,13 @@ +import re + from .html5 import omit_endtag from .util import attributes, esc_script, esc_style, escape, escape_special, mangle +CSS_SELECTOR = re.compile( + r'(?:#(?P[\w-]+))|(?:\.(?P[\w-]+))|(?:\[(?P[\w-]+)=["\']?(?P[\w\s/]+)["\']?\])' +) + class Builder: """Builder generates a document with .elemname(attr1="value", ...) syntax. @@ -114,6 +120,23 @@ def __call__(self, *_inner_content, **_attrs): self._(*_inner_content) self._endtag_close() return self + + def __getitem__(self, item): + """Add attributes to the current tag.""" + assert isinstance(item, str), "Attribute names must be strings in CSS selector syntax." + + classes = [] + kwargs = {} + for match in CSS_SELECTOR.finditer(item): + if match["id"]: + kwargs["id_"] = match["id"] + elif match["class"]: + classes.append(match["class"]) + elif match["attribute"]: + kwargs[match["attribute"]] = match["value"] + if classes: + kwargs["class_"] = " ".join(classes) + return self(**kwargs) def _(self, *_content): """Append new content without closing the current tag."""