Custom Roles
How to apply a special inline font style
Sphinx only supports a few inline text format options such as bold or italic. But sometimes, you need more options, such as a colored font or background or underlines.
Create
_static/css/custom.cssin your project if you haven’t already.Define the style you want to apply to your text for a descriptive class. For instance
.rbg { background-color: #ff9999; } .gfg { color: #2eb82e; } .ulined { text-decoration: underline; }
Open to the *.rst file, which should use those styles and add the references at the very top:
.. role:: rbg .. role:: gfg .. role:: ulined
Your styles can now be applied just like the built-in cross references.
Important
If you like to have your role(s) available in every *.rst file without the need for an declaration in all files, you can add the respective roles to the rst_prolog variable in your
conf.pyfile, like this:rst_prolog = """ .. role:: rbg .. role:: gfg .. role:: ulined """
Apply a style to a certain piece of text like this:
It is :ulined:`important` not to put a :rbg:`red background` on :gfg:`green text`.
This results in the following output:
It is important not to put a red background on green text.
How to apply a custom role containing raw HTML
Sometimes a special HTML content is needed to achieve the correct formatting in the HTML output.
For instance, the csv-table does not feature line breaks within cells, but a raw HTML substitution can add this feature.
Attention
I found out that having a raw-html substitution in the rst_prolog as
explained below leads to the sphinx-contrib/emojicodes to become non functional,
meaning that
no emojis will be displayed in the output HTML
no warning about the malfunction is shown
If you use the approach below, watch out for this error and revert the changes in case, it occurs. As an alternative, either
only add the substitution to the particular RST document, which needs it (like on the top of the document) like
.. |br| raw:: html <br /> Page Headline ============= ...
or use line blocks, like:
| Line 1 | Line 2 | Line 3 | Line 4
translating to
Line 1Line 2Line 3Line 4
Open the
conf.pyfile and create an rst_prolog variable, if not already existing.Add the following content:
1rst_prolog=""" 2.. |br| raw:: html 3 4 <br /> 5"""
This makes the substitution available on every RST file within the documentation.
Attention
The empty line 3 between the raw directive and its content (
<br />) is needed by Sphinx to differentiate between the directive’s option (even though raw does not allow any) and its content.Add the
|br|to the CSV file referenced by the.. csv-table::directive or into the directive content directly. For example.. csv-table:: Open Days Week 1, Monday |br| Tuesday |br| Wednesday Week 2, Monday |br| Thursday |br| Friday
renders into
Open Days Week 1
Monday
Tuesday
WednesdayWeek 2
Monday
Thursday
Friday