Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering newline character in VueJS

I'm creating a note app where users can add a note by entering multiline text in a textarea. When I save the note in Firebase it is being saved with newline (\n) characters which I want to visualize.

Therefore, I wrote a filter that replaces these characters with <br /> and that works great.
Though, now I need to render my data using {{{note.content}}} and a user can inject HTML, CSS, and JS that will be executed.
Should I use something like DOMPurify to validate the content or is there a way to safely render newline characters?

like image 740
Swimburger Avatar asked Apr 19 '16 21:04

Swimburger


3 Answers

As @shelvacu said the <pre> html tag preserves whitespaces.

However using it has one serious disadvantage: the tag itself inherits plenty of unnecessary styling from CSS frameworks that are used in project (e.g. Bootstrap).

To preserve whitespaces and avoid inheriting any unnecessary styles use:

<span style="white-space: pre;">Some whitespaced content</span> 

what will act exacly like the <pre> tag.

Be aware that white-space: pre remains text 'as it is' - if you would like to have additional line break when it's necessary use: white-space: pre-wrap.

See: w3schools.com CSS white-space Property

like image 175
Krzysiek Avatar answered Sep 28 '22 06:09

Krzysiek


Wrap the content in a pre element.

A <pre> element will preserve whitespace within it, eg:

This is followed by a newline, not that you can tell <br /> <br /> <pre>You can see the newline after me! Woohoo!</pre> 

Will result in:

This is followed by a newline, not that you can tell  You can see the newline after me! Woohoo! 

This way, you do not need to do any filtering of newlines.

like image 35
Shelvacu Avatar answered Sep 28 '22 05:09

Shelvacu


Use white-space: pre-line; CSS property.

As write in Mozzila Doc for pre-line value:

Sequences of white space are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

like image 44
Shiva127 Avatar answered Sep 28 '22 06:09

Shiva127