Skip to content

for convert_* functions, allow for tags with special characters in their name (like "subtag-name") #136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ def process_tag(self, node, convert_as_inline, children_only=False):
text = text_strip + newlines + next_text_strip

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

Expand Down
15 changes: 11 additions & 4 deletions tests/test_custom_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@
from bs4 import BeautifulSoup


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

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

def test_img():

def test_custom_conversion_functions():
# Create shorthand method for conversion
def md(html, **options):
return ImageBlockConverter(**options).convert(html)
return UnitTestConverter(**options).convert(html)

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

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


def test_soup():
html = '<b>test</b>'
Expand Down
Loading