Python Markdown nl2br extension

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 tried 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.


Solution 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.