I have a text being returned from SQL that may have newlines in it. However, since I’m putting the value in between <p></p> tags, it’s ignoring the newlines.
For example if the text in SQL is actually this (with a CRLF between lines):
foobar car
carbar foo
The HTML code becomes:
<p>foobar car
carbar foo</p>
Which is just rendering as:
foobar car carbar foo
Ultimately it seems that I want to detect a newline then add the appropriate HTML such as:
<p>foobar car</p><p>carbar foo</p>
or even
<p>foobar car<br/><br/>carbar foo</p>
Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how?
I noticed that there a function in PHP to handle exactly this case: nl2br (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn’t help me 🙂
It’s generally better to perform this kind of logic is your presentation code then your DB or middle-tier.
My Recommended approach would be to write some .net code to replace cr and lf with
<br/>tags. The code itself is straightforward, here is an example that will emulate your php nl2br function:You could also perform this transform in SQL using REPLACE() and CHAR() although it is preferable to perform this kind of transform in the presentation layer, not the database layer.
The SQL approach would be:
This would replace
CHAR(13)andCHAR(10)(cr and lf) with<br/>tags.A third option would be to render your text at preformatted text using the
<pre>tags although this is really only suitable for a narrow set of use-cases (such as displaying code as used here on StackOverflow)e.g.
which would render like this:
keeping spaces and new lines intact.