Search code examples
pythonrestructuredtextdocutils

reStructuredText not respecting subheadings


Here's a simple reST snippet:

deleting this line causes all subheadings to be rendered as h1 tags

I should be an h1
=================

I should be an h2
-----------------
foo            

I should also be an h2
----------------------
foo

and here's a demonstration of it being rendered:

with initial line: http://rst.ninjs.org/?n=ff67380d732a33c7844f350c240804d0
without initial line: http://rst.ninjs.org/?n=550ea2c1b4233affdce1d158c5dc4d99

I'm rendering reST using the following Python:

from docutils.core import publish_parts
parts = publish_parts(rest_content, writer_name="html")
html_snippet = parts['html_body']

How do I get subheadings (specifically, <h2> tags) without the initial line? Do have provide two levels of hierarchy above the subheadings? Naively providing a page header doesn't help: http://rst.ninjs.org/?n=e874f6eaad17c8ae7fd565f9ecb2212b


Solution

  • Don't promote the 1st title to document title.

    Note the settings_overrides param passed to publish_parts() in the example below:

    rest_content = """
    I should be an h1
    =================
    
    I should be an h2
    -----------------
    foo
    
    
    I should also be an h2
    ----------------------
    foo
    """
    
    from docutils.core import publish_parts
    parts = publish_parts(rest_content, writer_name="html",
            settings_overrides={'doctitle_xform':False})
    html_snippet = parts['html_body']
    
    print(html_snippet)
    

    And the output:

    <div class="document">
    <div class="section" id="i-should-be-an-h1">
    <h1>I should be an h1</h1>
    <div class="section" id="i-should-be-an-h2">
    <h2>I should be an h2</h2>
    <p>foo</p>
    </div>
    <div class="section" id="i-should-also-be-an-h2">
    <h2>I should also be an h2</h2>
    <p>foo</p>
    </div>
    </div>
    </div>