Felixkruemel
Felixkruemel

Reputation: 514

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?

Upvotes: 0

Views: 652

Answers (2)

Steve Piercy
Steve Piercy

Reputation: 15045

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',
]

Upvotes: 1

Itay Ziv
Itay Ziv

Reputation: 76

You can also use sphinxext-photofinish, the docs are somewhat lacking, but in general, you can leave your image tags as:

.. image:: picture.jpg
   :alt: Alt Text

And it should automatically generate a <picture> tag, try to convert to .webp and fill in the width/height. It is used in frc-docs if you want to see an example.

Upvotes: 0

Related Questions