diff --git a/README.rst b/README.rst index 6545a8c..b64318a 100644 --- a/README.rst +++ b/README.rst @@ -106,6 +106,13 @@ escape_underscores If set to ``False``, do not escape ``_`` to ``\_`` in text. Defaults to ``True``. +keep_inline_images_in + Images are converted to their alt-text when the images are located inside + headlines or table cells. If some inline images should be converted to + markdown images instead, this option can be set to a list of parent tags + that should be allowed to contain inline images, for example ``['td']``. + Defaults to an empty list. + Options may be specified as kwargs to the ``markdownify`` function, or as a nested ``Options`` class in ``MarkdownConverter`` subclasses. diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 82262d4..8cf56eb 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -75,6 +75,7 @@ class MarkdownConverter(object): default_title = False escape_underscores = True heading_style = UNDERLINED + keep_inline_images_in = [] newline_style = SPACES strip = None strong_em_symbol = ASTERISK @@ -278,7 +279,8 @@ class MarkdownConverter(object): src = el.attrs.get('src', None) or '' title = el.attrs.get('title', None) or '' title_part = ' "%s"' % title.replace('"', r'\"') if title else '' - if convert_as_inline: + if (convert_as_inline + and el.parent.name not in self.options['keep_inline_images_in']): return alt return '![%s](%s%s)' % (alt, src, title_part) diff --git a/tests/test_conversions.py b/tests/test_conversions.py index 6cf39ac..018b7c1 100644 --- a/tests/test_conversions.py +++ b/tests/test_conversions.py @@ -133,12 +133,13 @@ def test_hn_nested_simple_tag(): def test_hn_nested_img(): image_attributes_to_markdown = [ - ("", ""), - ("alt='Alt Text'", "Alt Text"), - ("alt='Alt Text' title='Optional title'", "Alt Text"), + ("", "", ""), + ("alt='Alt Text'", "Alt Text", ""), + ("alt='Alt Text' title='Optional title'", "Alt Text", " \"Optional title\""), ] - for image_attributes, markdown in image_attributes_to_markdown: - assert md('

A B

') == '### A ' + markdown + ' B\n\n' + for image_attributes, markdown, title in image_attributes_to_markdown: + assert md('

A B

') == '### A ' + markdown + ' B\n\n' + assert md('

A B

', keep_inline_images_in=['h3']) == '### A ![' + markdown + '](/path/to/img.jpg' + title + ') B\n\n' def test_hn_atx_headings():