Preserving a line-feed in SQL data when displaying in an HTML table?


I have this:

@data = Item.where("category = 'entrees'")

<% @data.each do |data| %>
    <td><%= data.item %></td>
    <td><%= data.comment %></td>
    <td><%= data.price %></td>
<% end %>

and I want this data in the Sqlite3 DB preserved when it is displayed the HTML table:

“Spring Rolls
- 4 per serve”

I have tried: “\n” and “br” in angle brackets with and without a trailing " /" but the line-feed is not preserved and the text is printed the table cell as literal instead of behaving as a control character.

Is there a way to do what I want?

Thanks, Phil.

You might have better luck on the rails-talk list – this list if for development of Rails itself, not the use of it.


I recategorized to rails talk

@philip_rhoades have you considered using a pre tag if you want to preserve spacing

<td>Spring Rolls<br>- 4 per serve</td> renders as your example. Perhaps you could show the code you’re using to substitute a br tag for the line break?

<td>Spring Rolls<br>- 4 per serve</td>

td>Spring Rolls<br />- 4 per serve</td>

Tried both - it works hard coded but not from SQL . .

Thanks, Phil.

If you need HTML direct from SQL you need to call html_safe on the string.

Note… be careful cause you may be opening yourself up to enormous amounts of nasty XSS attacks.

Ah . . right - good point . .


As I said – show the code you’re using to transform the raw string from the database.

Not sure what you mean - the code was in the original post?

I see some markup but no code that’s converting a newline to a break tag anywhere.

What exactly is the relevant table content? where “exactly” is the output of a select statement on that field?

Ah . . I see what you mean - I have not coded anything specifically - I thought that that would not be necessary and that what I want to do should be already able to be done with some existing facility . .

As I said in the OP, the data is in a Sqlite DB and the relevant field looks like:

“Spring Rolls
- 4 per serve”

Well, there you go – you need to explicitly transform that newline/whatever character that’s not shown in your “looks like” to a break tag.

1 Like

Try using the simple_format helper. That will (among many other things) convert a newline into a
tag. It will also convert two newlines into a paragraph break, wrapping everything before the two newlines in a P tag, and closing off at the \n\n and starting a new paragraph.

The key to using this is to not have any HTML in your database, just plain text. Running HTML through simple_format would probably make a mess of it.


1 Like

Thanks! That is just what I was looking for!