Python Markdown nl2br extension

会有一股神秘感。 提交于 2021-02-08 03:49:37

问题


I'm a beginner programmer, and i've been trying to use the python markdown library in my web app. everything works fine, except the nl2br extension.

when i try to convert text file to html using md.convert(text), it doesn't see to convert newlines to <br>.

for example, before i convert, the text is:

Puerto Rico

===========

------------------------------

### Game Rules





hello world!

after i convert, i get:

 <h1>Puerto Rico</h1>
<hr />
<h3>Game Rules</h3>
<p>hello world!</p>

My understanding is that the blank spaces are represented by '\n' and should be converted to <br>, but i'm not getting that result. Here's my code:

import markdown
md = markdown.Markdown(safe_mode='escape',extensions=['nl2br']) 
html = md.convert(text)

Please let me know if you have any idea or can point me in the right direction. Thank you.


回答1:


Try adding two or more white spaces at the end of a line to insert <br/> tags

Example:

hello  
world

results in

<p>hello <br>
world</p>

Notice that there are two spaces after the word hello. This only works if you have some text before the two spaces at the end of a line. But this has nothing to do with your nl2br extension, this is markdown standard.

My advice is, if you don't explicitly have to do this conversion, just don't do it. Using paragraphs alias <p>-tags is the cleaner way to seperate text regions.

If you simply want to have more space after your <h3> headlines then define some css for it:

h3 { margin-bottom: 4em; }

Image if you do spacing with <br>-tags after your headlines in all your 500 wiki pages and later you decide that it's 20px too much space. Then you have to edit all your pages by hand and remove two <br>-tags on every page. Otherwise you just edit one line in a css file.




回答2:


Found this question looking for a clarification myself. Hence adding an update despite being 7 years late.


Reference thread on the Python Markdown Project: https://github.com/Python-Markdown/markdown/issues/707

Turns out that this is indeed the expected behaviour, and hence, the nl2br extension converts only single newlines occurring within a block, not around it. Which means,

This is
a block

This is a different
block

gets converted to

<p>This is<br/>block</p>\n<p>This is a different<br/>block</p>

but when you have distinct, separate blocks,

Puerto Rico

===========

------------------------------

### Game Rules





hello world!

all surrounding newlines are collapsed, and no <br/> tags are injected.

<h1>Puerto Rico</h1>
<hr />
<h3>Game Rules</h3>
<p>hello world!</p>


来源:https://stackoverflow.com/questions/12199819/python-markdown-nl2br-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!