Sphinx - add custom field / variable to be used in HTML template

I am trying to extract meta information from .rst

files to be included in an HTML template. I assumed that if I put something like

.. :newVariable: My Text

      

to the .rst file and then generate the HTML using my own template, I could include the newVariable

HTML in the header. But that won't work. I tried a couple of things to no avail.

Is this allowed without changing the Sphinx sources?

+3


source to share


2 answers


In your .rst file, place at the top a list of fields with the name and value of the variable you want to pass. The information is meta

not required, but is shown so you can see where to put your code.

.. meta::
   :author: My Company, Inc.
   :description: Introduction to ...
   :copyright: Copyright © 2014 My Company, Inc.

:my-variable: my variable value

.. _introduction:

==================================================
Introduction to ....
==================================================

      

In your template, you can now access my-variable

using code like:



{%- set my-variable = '' %}
{%- set my-variable_key = 'my-variable' %}
{%- if meta is defined %}
    {%- if my-variable_key in meta.viewkeys() %}
        {%- set my-variable = meta.get(my-variable_key) %}
    {%- endif %}
{%- endif %}

      

Now you can use my-variable

its value as well.

Note that the template meta

refers to the second list of fields; metatags

references HTML generated with docutils for header meta tags built from .. meta::

. They are two different objects with the same name ...

+3


source


I'm not sure if this answers your question exactly, but there is a dictionary called html_context

that you can put in your sphinx config file (conf.py) that allows you to define custom variables, which you can then display in your html templates. You can check the docs here: http://sphinx-doc.org/config.html#confval-html_context

In my application, I had a list of software release dates that I would like to display in my index.html doc splash page. I configured it like this:

In release.py versions:

RELEASES = [                                                               
   ( "Jun 05, 2014", "095", "" ),                                                
   ( "May 28, 2014", "094", "" ),                                                
   ( "Apr 29, 2014", "093", "" ),
   ...
]

      



In conf.py:

# Get list of releases for index page rendering                            
import releases                                    
html_context = {                                                                 
    'releases' : releases.RELEASES,                                   
}  

      

In index.html:

 {%- for release in releases %}                                         
   <p><span class="style4"><em><strong>{{ release[0] }} ... {{ release[1] }} was released ... </p>
 {%- endfor %}    

      

+2


source







All Articles