Search code examples
htmlpython-sphinxrestructuredtext

How do you embed a <picture> tag in sphinx docs?


I have found the following question: How do we embed images in sphinx docs?

However this image tag assumes the file is in jpg or png:

.. image:: picture.jpg
   :width: 200px
   :height: 100px
   :scale: 50 %
   :alt: alternate text
   :align: right

The issue with that is that jpg and png are not modern formats (also creates a bad speed index in Lighthouse/Google PageSpeed Insights: enter image description here). I would like to use a html tag with a srcset containing of two identical files in two formats. Something like that:

<picture>
   <source srcset="diagram.avif" type="image/avif">
   <img src="diagram.jpg" width="620" height="540">
</picture>

This will serve the way smaller image to all modern browsers, but will serve the png to browsers which don't support avif (e.g. IE). How can you do that in sphinx docs / RST?


Solution

  • Use the raw directive and your code.

    .. raw:: html
    
        <picture>
          <source srcset="diagram.avif" type="image/avif">
          <img src="diagram.jpg" width="620" height="540">
        </picture>
    

    To copy arbitrary static files, put them in a directory relative to the documentation source files, say _static, place the files there, and then configure the value html_static_path in your conf.py. For example:

    html_static_path = [
        '_static',
    ]