Python Markdown nl2br extension - python

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.

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.

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>

Related

How to share python code in stackoverfolw? [migrated]

How do I post text so that it is formatted as code?
What do I need to do so that my code shows up properly—not escaped or removed—when posted? And how do I get the correct syntax highlighting?
For more information, see "How do I format my posts in HTML or Markdown?" in the Help Center.
Return to FAQ index
For inline code (that does not hold newlines), any of the following will work:
Enclose with backticks: `<html>`.
Embed within <code> tags, and manually encode HTML entities: <code><html></code>
Select the partial text and hit CtrlK (⌘K on OS X) or click the {} button above the editor (pictured below)
For blocks of code, to preserve newlines, use one of the following methods:
Use the {} button above the editor (pictured below)
Paste your code, select the full lines, and hit CtrlK (⌘K on OS X)
Use fenced code blocks by surrounding your code with ``` or with ~~~
Opening and closing fence have to be on their own line, and can be indented with up to three spaces
More than three backticks or tildes can be used, as long as the closing fence uses the same character and is at least as long as the opening fence
Indent everything four (4) spaces or one (1) tab
Ensure there is a blank line between the top of the block and other text
Encase in <pre> or <pre><code> tags (in that order; using <code><pre> is invalid), and encode HTML entities (like < for <) yourself
In <pre> blocks, HTML tags are applied rather than rendered as text. But in <pre><code> blocks with Syntax highlighting (see below), all HTML tags are stripped out. A lang-none language hint (see below) prevents syntax highlighting and keeps HTML tags.
(Code highlighting is disabled by default on meta sites.)
Code copy/pasted from an IDE is often already tabbed. When rendering, tabs are replaced with spaces.
Code within a blockquote
To include code within a blockquote, make sure to include the space after the > as well as the four spaces before the code.
> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
> for(;;)
echo 'badger ';
Or, put the blockquote character (and its following space) at the beginning of every blank line, including the one immediately before the code.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
>
for(;;)
echo 'badger ';
You can also use fenced code blocks within quotes:
> Text before code
> ```
> for (;;;)
> echo 'badger';
> ```
> Text after code
Code within a numbered or bulleted list
If your code appears inside a list, you must indent an additional four spaces for each level of nesting.
- First bullet (is the deepest)
for(;;)
echo 'ow ';
- Second bullet
If you want a block of code to follow a list but not be nested under the final list item, you can use an HTML comment as a "breakpoint". If you do this, the code block only needs to be indented with the normal four spaces:
- First bullet
- Second bullet
<!-- -->
for(;;)
echo 'ow ';
Syntax highlighting
Highlight.js is used to add colour to the code, but only if the language can be uniquely determined given the tags of the question, or if manual hints have been provided.
For any code block, you can use these HTML comments to specify the language:
<!-- language: lang-or-tag-here -->
code goes here
<!-- language: lang-or-tag-here -->
code goes here
<!-- language: lang-or-tag-here -->
```
code goes here
```
<!-- language: lang-or-tag-here -->
~~~
code goes here
~~~
You can also specify the syntax for all codeblocks in your post with the language-all hint:
<!-- language-all: lang-or-tag-here -->
code goes here
More text not in code blocks
code goes here
Alternatively, if you use fenced code blocks, you can specify the language right after the first fence:
```lang-or-tag-here
code goes here
```
~~~lang-or-tag-here
code goes here
~~~
This goes for fenced code blocks elsewhere as well:
> ```javascript
> for (;;;) {
> console.log('badger');
> }
> ```
See the full specification and list of languages hints.
Note that:
The HTML comments must not be indented
The blank line between <!-- language: ... --> and the indented code block is required
The space between language: and the language is required
When using a tag to specify language, the tag name is case-sensitive
If you combine the fenced style with the HTML comments, the HTML comments are ignored
If no language is defined then no highlighting occurs at all. But in the preview, or if multiple language tags define very different languages and no manual definition is used, a default highlighting is used in which Prettify makes a best guess.
There is a delay before the preview text highlighting is applied after you stop editing your markdown source, of around 5 seconds.
Stack Snippets – Executable JavaScript/HTML/CSS snippets
Stack snippets can group a JavaScript, HTML and CSS code snippet and make them runnable. This feature can be accessed by the icon that looks like a page with a <> on it. Alternatively, you can press CtrlM (⌘M on OS X).
The code snippet tool allows you to format code automatically using the Tidy button on the left. You can use this option to take care of replacing tabs by spaces, correct code indentation, and general improvement of readability
Once you save your snippet, you’ll get something like this in the editor:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// JavaScript code
<!-- language: lang-css -->
/* CSS code */
<!-- language: lang-html -->
HTML code
<!-- end snippet -->
If you delete the begin snippet and end snippet comments, you’re left with three adjacent code snippets that are not executable. You may also keep a single block of code which will have the correct formatting and indentation.
Using mobile devices
One sometimes needs to press and hold the regular single quote to get the backtick.
Backticks in text
To include a backtick without accidentally starting some inline code, escape it: \`
like \` so yields: like ` so
<kbd>Alt Gr</kbd>+<kbd>\`</kbd> gets `|` yields: Alt Gr+` gets |
Backticks within backticks
To use literal backticks within a code span, use any unique number of multiple backticks as the opening and closing delimiters: both ``literal backtick (`) here`` and, for example, ``````literal backtick (`) here`````` yield literal backtick (`) here. This works in comments too.
To use literal backticks at the start and/or end, add one space to both the opening and closing delimiters: `` `<html>` `` yields `<html>`, and `` $` `` yields the Perl $` operator. In comments, the additional space in the delimiters is not supported. Instead, escape the backtick: `\`<html>\`` and `$\`` to get `<html>` or $` in a comment.

How to insert indents into html code tag?

I'm trying to put some python code in html document. I am using code tag. Example
<code>
for iris, species in zip(irises, classification):
if species == 0:
print(f'Flower {iris} is Iris-setosa')
</code>
The problem is, page doesn't see new lines and indents. I can handle new lines with br tag but I didn't find anything to make indent. I tried pre tag, but I have to remove all indents in html document, and with several indents in it, it starts to look very ugly. Propably I could use but using 4,8 or 12 in one line doesn't seem to be good idea. Is there anything else I can do to format my code?
The parser will ignore white space characters in the source code. you can may <pre> or <br/> or fake it with CSS. but the solution you proposed is also valid and works, but as you stated it is ugly. if you are going for that you can use &Tab; char and it will create a tab indent; it makes more sense to use it instead of 4 x but you still need to put it inside <pre> tag to avoid being ignored by the parser.

django Built-in template tags and filter Cut command not removing second space

My database stored phone numbers as "(123) 456-7890 "
I need to remove all spaces from a phone number so that I can make calls via Cisco phone.
`<td>{{` contact.Phone | cut:" "}}</td>
But django is displaying html as:
(123)456-7890
I tried :
{{contact.Phone|cut:"("|cut:")"|cut:"-"|cut:" "}}
and
{{contact.Phone|cut:"("|cut:" "|cut:" "}}
The documentation makes it seem like one cut function should clear both spaces.
Thanks
Maybe there's another white character at the end? I'd recommend using spaceless tag. According to docs, it:
removes whitespace between HTML tags. This includes tab characters and
newlines.
{% spaceless %}{{contact.Phone|cut:"("|cut:")"|cut:"-"|cut:" "}{% endspaceless %}
Edit: as pointed by #iklinac in the comments below |cut:" " is still needed as spaceless is not allowed to modify variables you passed to the template.

Detecting newline character on user's input (web2py)

I have the following table:
db.define_table('comm',
Field('post','reference post', readable=False, writable=False),
Field('body','text', requires=IS_NOT_EMPTY()),
auth.signature
)
and in a python function, the following code:
form=SQLFORM(db.comm).process()
I call that form in the returned view by the python function
{{=form}}
The problem is when the user inputs two or more paragraphs, it doesn't detect the newline character. How can I fix that?
Use pre tag to display the content in which you want to detect newline character.
<pre>
The HTML pre element (or HTML Preformatted Text) represents
preformatted text. Text within this element is typically displayed in
a non-proportional ("monospace") font exactly as it is laid out in the
file. Whitespace inside this element is displayed as typed.
{{for post in comments:}}
<pre>{{=post.body}}</pre>
{{pass}}
Assuming you are referring to the subsequent display of the user input in a view, you could use a <pre> tag: http://www.w3schools.com/tags/tag_pre.asp. However, you might need some CSS to get the font/styling you like (by default, the browser will use alternative styling with a fixed-width font).
You could also replace the newlines with <br> tags:
{{=XML(record.body.replace('\n', '<br>'), sanitize=True, permitted_tags=['br/'])}}
Because the text now contains <br> HTML tags, it is necessary to wrap it in XML() to prevent web2py from escaping the HTML -- but you also want to sanitize the text and allow only <br> tags to prevent malicious code from being executed.

Process whitespaces from user input

The only reason why I include Python in the question is that PHP has the nl2br function that inserts br tags, a similar function in Python could be useful, but I suspect that this problem can be solved with HTML and CSS.
So, I have a form that receives user`s input in a textarea. I save it to the database, which is Postgres and then when I display it, it doesn't include the line breaks the user supplied to separate paragraphs.
I tried using the white-space CSS property on the paragraph tag:
white-space: pre
or
white-space: pre-wrap
But, this is weird, the result was separated lines but the first line aligned in the middle:
including text-align:left didn't solve the problem. I'm sure there is a simple solution to this.
I would suggest to replace newline characters with <br /> either before storing it in the database (only once) or when fetching it (see comment).
With Python:
import re
myUserInput = re.sub('(?:\r\n|\r|\n)', '<br />', myUserInput)
With JavaScript (see jsfiddle):
myUserInput = myUserInput.replace(/(?:\r\n|\r|\n)/g, '<br />');

Categories

Resources