Skip to content

Commit b1759ff

Browse files
authored
Merge pull request #209 from canonical/wd-20353
feat: Add function that allows injecting custom css
2 parents 2100c61 + a61a767 commit b1759ff

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
### 6.2.0 [28-04-2025]
2+
**Added** _inject_custom_css def
3+
A function that finds css directives (`[style=CLASSNAME]`) in the soup and applies to them to the next found element.
4+
15
### 6.1.1 [12-03-2025]
26
**Updated** EngagePages class
37
Pass values for the provided keys, even if the values are empty or null, as they can be a filter themselves.

canonicalwebteam/discourse/parsers/base_parser.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,7 @@ def _process_topic_soup(self, soup):
536536
soup = self._replace_polls(soup)
537537
soup = self._remove_trailing_numbers_from_headings(soup)
538538
soup = self._add_anchor_links(soup)
539+
soup = self._inject_custom_css(soup)
539540

540541
return soup
541542

@@ -859,3 +860,29 @@ def _add_anchor_links(self, soup):
859860
heading.append(anchor)
860861

861862
return soup
863+
864+
def _inject_custom_css(self, soup):
865+
"""
866+
Given HTML soup, finds style identifiers and applies the given
867+
class to the element directly next.
868+
869+
Example:
870+
[style=p-table--wide-table] applies the class 'p-table--wide-table'
871+
"""
872+
custom_css_directives = soup.find_all(
873+
string=re.compile(r"\[style=(.*?)\]")
874+
)
875+
876+
for css_directive in custom_css_directives:
877+
match = re.search(r"\[style=(.*?)\]", css_directive)
878+
if match:
879+
style_class = match.group(1)
880+
next_element = css_directive.find_next_sibling()
881+
if next_element:
882+
if "class" in next_element.attrs:
883+
next_element["class"].append(style_class)
884+
else:
885+
next_element["class"] = [style_class]
886+
css_directive.extract()
887+
888+
return soup

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
setup(
66
name="canonicalwebteam.discourse",
7-
version="6.1.1",
7+
version="6.2.0",
88
author="Canonical webteam",
99
author_email="webteam@canonical.com",
1010
url="https://github.com/canonical/canonicalwebteam.discourse",

0 commit comments

Comments
 (0)