Mitar
Mitar

Reputation: 6980

In Python sphinx, how to link to a file in _static directory

I have some code and data samples I copy to _static directory and I would like to link to those files in documentation, something like:

.. _pca-run.py: _static/example.data

But the problem is that sphinx does not create a proper relative link to this file, but just copies the values as it is. So for nested files where _static is not in the same directory links do not work.

Upvotes: 25

Views: 20917

Answers (2)

Kevin Horn
Kevin Horn

Reputation: 4285

What you want is the :download: text role. (as Mitar mentioned in his comment).

https://www.sphinx-doc.org/en/stable/usage/restructuredtext/roles.html#role-download

Using this will tell Sphinx to copy the given file to a "_downloads" directory and create a hyperlink to it. This was originally intended to be used for downloadable files, like perhaps PDFs (in html output) or tarballs, or whatever. It works just fine for any other non-ReST file though.

If you really wanted, you could write an extension to do this, but I've never seen a need to, since :download: does exactly what I want.

Upvotes: 20

Raffi
Raffi

Reputation: 3375

Just find the right answer to this for images: preprend the path of the target file with /. For images referenced from an automodule

.. image:: some_file.png

will refer to the file some_file.png relative to the python file currently being processed, while

.. image:: /some_file.png

will refer to the file some_file.png relative to the location of the conf.py. This way, there is no need to pollute the source hierarchy with images.

Upvotes: 10

Related Questions