Skip to content

Commit 1b33330

Browse files
for convert_* functions, allow for tags with special characters in their name (like "subtag-name") (#136)
support custom conversion functions for tags with `:` and `-` characters in their names by mapping them to underscores in the function name
1 parent 3bf0b52 commit 1b33330

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

Diff for: markdownify/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@ def process_tag(self, node, convert_as_inline, children_only=False):
172172
text = text_strip + newlines + next_text_strip
173173

174174
if not children_only:
175-
convert_fn = getattr(self, 'convert_%s' % node.name, None)
175+
fn_name = 'convert_%s' % node.name.translate(''.maketrans(':-', '__'))
176+
convert_fn = getattr(self, fn_name, None)
176177
if convert_fn and self.should_convert_tag(node.name):
177178
text = convert_fn(node, text, convert_as_inline)
178179

Diff for: tests/test_custom_converter.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,29 @@
22
from bs4 import BeautifulSoup
33

44

5-
class ImageBlockConverter(MarkdownConverter):
5+
class UnitTestConverter(MarkdownConverter):
66
"""
7-
Create a custom MarkdownConverter that adds two newlines after an image
7+
Create a custom MarkdownConverter for unit tests
88
"""
99
def convert_img(self, el, text, convert_as_inline):
10+
"""Add two newlines after an image"""
1011
return super().convert_img(el, text, convert_as_inline) + '\n\n'
1112

13+
def convert_custom_tag(self, el, text, convert_as_inline):
14+
"""Ensure conversion function is found for tags with special characters in name"""
15+
return "FUNCTION USED: %s" % text
1216

13-
def test_img():
17+
18+
def test_custom_conversion_functions():
1419
# Create shorthand method for conversion
1520
def md(html, **options):
16-
return ImageBlockConverter(**options).convert(html)
21+
return UnitTestConverter(**options).convert(html)
1722

1823
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == '![Alt text](/path/to/img.jpg "Optional title")\n\n'
1924
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == '![Alt text](/path/to/img.jpg)\n\n'
2025

26+
assert md("<custom-tag>text</custom-tag>") == "FUNCTION USED: text"
27+
2128

2229
def test_soup():
2330
html = '<b>test</b>'

0 commit comments

Comments
 (0)