Use image description text as "alt", drop title

The current RecommonMark specification on images [0] says that:

    ![foo](/url "title")

should render as

    <p><img src="/url" alt="foo" title="title" /></p>

which means that "foo" should be the `alt` attribute, and "title" should
be the `title` attribute.

Currently, `recommonmark` will:

1. set the `alt` attribute to "title"
2. render "foo" as literal text following the image element.

Neither yields results in line with the RecommonMark standard, resulting
in the following when transformed to HTML:

    <p><img src="/url" alt="title" />foo</p>

While it might be surprising that `alt` is set to "title", the more
pressing issue is how the alt text becomes literal text within the
paragraph, typically not rendering well.

This commit instead makes `recommonmark`:

1. set the `alt` attribute to "foo"
2. drop "title" altogether since the `title` attribute is not supported
   in Docutils [1].

1 coincides with the specification, and 2 is in my mind the least
surprising solution within the capabilities of Docutils. The HTML will
now be:

    <p><img src="/url" alt="foo" /></p>

only differing in the missing `title` attribute when compared to the
specification.

[0]: https://spec.commonmark.org/0.28/#images
[1]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#image
This commit is contained in:
Daniel Andersson 2019-04-06 12:56:27 +02:00
parent 815d75ea50
commit 059e95d6f3
3 changed files with 5 additions and 4 deletions

View file

@ -178,8 +178,9 @@ class CommonMarkParser(parsers.Parser):
img_node = nodes.image()
img_node['uri'] = mdnode.destination
if mdnode.title:
img_node['alt'] = mdnode.title
if mdnode.first_child and mdnode.first_child.literal:
img_node['alt'] = mdnode.first_child.literal
mdnode.first_child.literal = ''
self.current_node.append(img_node)
self.current_node = img_node

View file

@ -232,7 +232,7 @@ class TestParsing(unittest.TestCase):
<?xml version="1.0" ?>
<document source="&lt;string&gt;">
<paragraph>
<image alt="title" uri="/url">foo</image>
<image alt="foo" uri="/url"></image>
</paragraph>
</document>
"""

View file

@ -129,7 +129,7 @@ class GenericTests(SphinxIntegrationTests):
def test_image(self):
output = self.read_file('index.html')
self.assertIn(
'<p><img alt="Example" src="image.png" />foo</p>',
'<p><img alt="foo" src="image.png" /></p>',
output
)