reStructuredText not respecting subheadings
Asked Answered
S

3

5

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

Septuagint answered 8/3, 2012 at 14:8 Comment(0)
I
10

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>
Inmost answered 8/3, 2012 at 15:23 Comment(1)
Fantastic, I didn't know about that setting, let alone that it was on by default. Much appreciated.Septuagint
P
1

Just had the same problem. The accepted solution did not work for me. However, the following code did:

content = publish_parts(
    rest_content,
    writer_name='html',
    settings_overrides={'initial_header_level': 2})
html = content['html_body']
Pendley answered 29/10, 2015 at 19:24 Comment(0)
V
0

ReST doesn't care what symbol you use for each level, "=" is merely a convention. So if you remove the first one it then sees "-" as denoting a h1. I don't think there is a way around this unfortunately.

Vigilantism answered 8/3, 2012 at 14:21 Comment(2)
Any symbol at all? Are you saying that the string deleting this line is treated as a heading? If not, why does removing that line change the heading rendering?Septuagint
No, it has to be a series of non-alphanumeric characters, e.g. ===== or ~~~~~. See the ReST docsVigilantism

© 2022 - 2025 — McMap. All rights reserved.