Search code examples
pythonpython-sphinxrestructuredtextdocutils

Using rst2html5.py to get html body only


With

rst2html5.py foo.rst  --math-output=MathJax > foo.html

where foo.rst is e.g.

The area of a circle is :math:`A_\text{c} = (\pi/4) d^2`.

.. math::

         \frac{ \sum_{t=0}^{N}f(t,k) }{N}

I get back a standalone html page foo.html. What if I just wanted to the body of the html, e.g. so that I could insert into another html template?

I know I could do something like

from docutils import core
text = open('foo.rst').read()
document = core.publish_parts(text, writer_name='html5')

and then get document['body'], but this does not deal with the math directive in a MathJax way

I.e. I want this body to be

<p>The area of a circle is <span class="math">\(A_\text{c} = (\pi/4) d^2\)</span>.</p>
<div class="math">
\begin{equation*}
\frac{ \sum_{t=0}^{N}f(t,k) }{N}
\end{equation*}
</div>

and not the usual

<p>The area of a circle is <span class="formula"><i>A</i><sub><span class="text">c</span></sub> = (<i>π</i> ⁄ 4)<i>d</i><sup>2</sup></span>.</p>
<div class="formula">
<span class="fraction"><span class="ignored">(</span><span class="numerator"><span class="limits"><sup class="limit"><i>N</i></sup><span class="limit">⎲</span><span class="limit">⎳</span><sub class="limit"><i>t</i> = 0</sub></span><i>f</i>(<i>t</i>, <i>k</i>)</span><span class="ignored">)/(</span><span class="denominator"><i>N</i></span><span class="ignored">)</span></span>
</div>

Solution

  • First, if you use rst2html5:

    pip install rst2html5
    

    Then, you can use this piece of code to get the body:

    from docutils.core import publish_parts
    from rst2html5_ import HTML5Writer
    text = r'''
    The area of a circle is :math:`A_\text{c} = (\pi/4) d^2`.
    
    .. math::
    
           \frac{ \sum_{t=0}^{N}f(t,k) }{N}
    '''
    body = publish_parts(writer=HTML5Writer(), source=text)['body']
    

    You'll get this:

    <p>The area of a circle is
        <span class="math">\(A_   ext{c} = (\pi/4) d^2\)</span>
    .</p>
    <span class="math">\(\frac{ \sum_{t=0}^{N}f(t,k) }{N}\)</span>