2012-03-08 125 views
5

這裏有一個簡單的REST片段:reStructuredText的不尊重副標題

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 

,這裏是它的渲染演示:

與初始行:http://rst.ninjs.org/?n=ff67380d732a33c7844f350c240804d0
無初始行:http://rst.ninjs.org/?n=550ea2c1b4233affdce1d158c5dc4d99

我使用以下Python渲染reST:

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

如何在沒有初始行的情況下獲取子標題(特別是<h2>標記)?小標題上方是否提供了兩級分層結構?天真地提供頁面標題並沒有幫助:http://rst.ninjs.org/?n=e874f6eaad17c8ae7fd565f9ecb2212b

回答

8

不要宣傳文檔標題的第一個標題。

注意settings_overrides PARAM傳遞給publish_parts()在下面的例子:

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) 

和輸出:

<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> 
+0

太棒了,我不知道這個設置,更不用說它默認啓用了。非常感激。 – 2012-03-09 13:54:16

0

ReST不關心你爲每個級別使用什麼符號,「=」只是一個約定。所以如果你刪除第一個,它會看到「 - 」表示h1。不幸的是,我認爲沒有辦法解決這個問題。

+0

任何符號呢?你是說「刪除這一行」字符串被視爲一個標題?如果沒有,爲什麼刪除該行更改標題渲染? – 2012-03-08 14:57:38

+1

不,它必須是一系列非字母數字字符,例如=====或~~~~~。查看[ReST文檔](http://docutils.sourceforge.net/docs/user/rst/quickstart.html#sections) – aquavitae 2012-03-08 15:12:07

1

剛剛有同樣的問題。接受的解決方案並不適合我。但是,下面的代碼所做的:

content = publish_parts(
    rest_content, 
    writer_name='html', 
    settings_overrides={'initial_header_level': 2}) 
html = content['html_body']