Line breaks not displaying in view - ruby-on-rails

I have Person.description with the following stored in the database:
jnkl
fdsfdsf
fdsf
fsdfdsfs fds fd sf sdf ds
How do I display this with the line-breaks in the view? It is currently displaying all on one line and I don't understand why.

you should use the simple_format helper:
<%= simple_format #person.description %>
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 301
def simple_format(text, html_options = {}, options = {})
wrapper_tag = options.fetch(:wrapper_tag, :p)
text = sanitize(text) if options.fetch(:sanitize, true)
paragraphs = split_paragraphs(text)
if paragraphs.empty?
content_tag(wrapper_tag, nil, html_options)
else
paragraphs.map! { |paragraph|
content_tag(wrapper_tag, raw(paragraph), html_options)
}.join("\n\n").html_safe
end
end

The reason why, is that in plain HTML, outside of containing tags such as 'xmp', line breaks aren't rendered as linebreaks, for the most part they are ignored. For them to show up, you need to replace them with 'br' tags, or something else that has a style or structure associated with it, like p tags, or even divs, depending on the content is.
This should do what you ask:
#person.description.gsub(/\n/, '<br />')
The built in Rails helper simple_format will also work, using p tags
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

I also use
#person.description.gsub(/\n/, '<br/>').html_safe
to display them in the view

Instead of replacing \n to <br> tags, which would consume a lot of processing if its a huge text, use css white-space: pre to break lines on \n.
Source: An html tag other than a textarea where \n is correctly interpreted

simple_format did not suit my needs as I want to be able to show multiple line breaks. simple_format makes 2 or more line breaks a paragraph.
So, I used css white-space: break-spaces; instead. The only current drawback is the browser support is 89.5% now.

Related

Excess spaces wile rendering multiline string in Rails 5

I end up with strange bug (feature?):
Here is how test.html.erb file looks like:
<textarea><%= "a\nb\nc" %></textarea>
and in rendered textarea I expect something like that:
a
b
c
But I got:
Where these excess spaces came from?
Rails 5.0.0.beta2
UDP: I should mention it before, but I have the same problem while using f.text_area inside of form_for block. It looks like:
.form
=form_for article do |f|
.form-group
=field_label f, :text, true
=f.text_area :text, class: %w(form-control), rows: 20, placeholder: t('placeholder.article_text')
(HAML)
I end up with it, and just simplified the exploit to simple erb file with one string
UDP2:
Here how it looks with simple_format: <textarea><%= simple_format("a\nb\nc") %></textarea>
I should clearify some thing: this textarea is used to edit article text. And then it (text) will be processed with markdown processor (RDiscount) before appears in html page. I have no any idea, why I should use simple_format to display raw text in textarea and why this
should became this
after save?
In HAML, use
~ f.text_area :text
instead of
= f.text_area :text
The ~ operator suppresses "pretty" newlines in HAML, which is useful with TEXTAREA and PRE tags. See Whitespace preservation in HAML for more information.
<textarea><%= "a\r\nb\r\nc" %></textarea>
\n is new line it will take to next line at same position where you was in previous line \r is carriage return mean move to start of line.
But I wont recommend this approach You should use <br/> tag instead
so use
<textarea><%= WhatEverTheTextIs.gsub(/\n/, '<br/>').html_safe %></textarea>
This will replace all new line characters to <br> tag
One more easy solution is to use simple_format i-e:
<textarea><%= simple_format(YOUR_TEXT_HERE) %></textarea>
UPDATE
Here is the code to use for form helper
.form
=form_for article do |f|
.form-group
=field_label f, :text, true
=f.text_area :text,:value=>simple_format(article.text), class: %w(form-control), rows: 20, placeholder: t('placeholder.article_text')
I just ran into the exact same problem. It all comes down to whitespace in your templates and layouts. In my case my main application is using HAML and has an application.html.haml with a section like so
#content.container{tabindex: "-1"}
.row
- if content_for?(:left_nav)
.col-md-3.sidebar
= yield(:left_nav)
.col-md-9
= flash_helper
= yield
%footer
= render :partial => 'shared/footer'
That's at least 10 spaces before the "yield" of the main content.
Then I was using a view from a gem that was in ERB, not HAML. But, since my main application layout is HAML, the view rendering/handling goes through the HAML renderers. HAML has dealt with whitespace and texareas already, but when the final and complete view is rendered, all of the extra whitespace from the main layout is included in the html and causes the content of the textarea to be indented.
Why is the first row not indented? Because the HAML "preserve" function cleans up the whitespace for the first row in the text area. See https://github.com/haml/haml/issues/516.
For me, the easy fix is to configure HAML to use "ugly" mode. This gets rid of all the leading whitespace when rendering the views. There is more about "ugly" mode and newlines in textareas in the HAML FAQ. To configure HAML to use ugly mode:
To improve performance, Haml defaults to {Haml::Options#ugly "ugly" mode} in Rails apps running in production. Ugly mode is when whitespace is stripped out, and this can cause issues occassionally.
If you are using Rails, you can change the default behaviour by creating a config/initializers/haml.rb file and adding in the following line.
Haml::Template.options[:ugly] = true
Links I found helpful while researching this:
https://github.com/haml/haml/issues/643
ERB view embedded in a Haml layout: what to do about whitespace now? (although the proposed solution didn't work for me b/c the ERB view would always be picked up before the HAML view)
https://github.com/haml/haml/blob/master/lib/haml/buffer.rb (fix_textareas)
https://github.com/haml/haml/blob/master/lib/haml/helpers.rb (specifically the preserve method)
My versions are Rails 4.2.6 and HAML 4.0.7

line break for a string placeholder in ruby

<%= f.text_area :comment, placeholder: "Comment on your track or" + \n + "share your favorite lyrics" %>
How can I get the placebolder to line break like
Solution was just to add white space so the next line wraps:
placeholder: "Comment on your track or share your favorite lyrics" %>
Pretty ugly but least complicated
The newline character \n should be included between the double, however HTML does not allow for line feed, but Thomas Hunter suggested an hack which consists in using a bunch of white spaces, like so:
<%= f.text_area :comment, placeholder: "Comment on your track or share your favorite lyrics" %>
You can also opt to use the title attribute instead.
In Ruby, in general "\n" is the new line character.
e.g.:
puts "first line\nsecond line"
=>
first line
second line
However, in your case:
you seem to try to use the newline character in an .erb expression <%= ... %>
That does not work, because that will only format the newline in the raw HTML souce,
but in the formatted HTML you will not see the newline! :-)
To see the newline in the formatted HTML, you need to do something like this:
either put the two strings in separate DIVs or SPANs
or put a <br /> in the string instead of the "\n" -- <br \> is the HTML newline symbol
You're creating HTML code. HTML does not care about whitespace in the actual code. What you need is a break in the HTML itself. However, it seems per this other question Can you have multiline HTML5 placeholder text in a <textarea>? that HTML does not allow line breaks in the placeholder field.

converting plain text to html

My rails 3 app receives emails. Some of them are plain text. When the app displays them to the user I want them to be properly formatted. In other word I want to encode plain text into html. For example: "Hello\n\nHello" => HelloHello (or something like it).
Of course I can write my own 4 lines of code but I am sure those 4 lines have already be written, tested and wrapped in some nice method call.
I know I'm a little late, but I actually think the proper solution to this, at least within Rails, is to leverage the simple_format helper method provided from ActionView::Helpers::TextHelper.
Wrap your text in a Pre tag:
<%= content_tag('pre', "Hello\n\nHello") %>
Using #html_safe, let me explain with an example:
If in your controller the variable is:
#str = "<h1>Hi</h1>"
Then in the view:
<%= #str.html_safe %>
#Batkins has the right answer, which should be accepted.
if someone who is still looking,
Converting plain text to HTML
<%= simple_format("plain text") %>
Converting HTML to proper plain text
text.html_safe
The simple_format is TextHelper module so you if you want to use simple_format method in controller
include ActionView::Helpers::TextHelper
in your controller
render :text => "bla bla bla"
it be useful
http://apidock.com/rails/ActionView/Rendering/render

Showing linebreaks in Rails3

I store the linebreaks as "line\n\nline" in the database.
When i am displaying it, I convert it using this method:
def showLineBreaks(from_textarea)
from_textarea.gsub(/\n/,"<br/>")
end
But these renders the text as
line<br><br>line
instead of showing the linebreaks.
What is the right way to do this?
You probably need to flag your content as html_safe for it to display properly, otherwise the view will render it as the string should be displayed.
<%= showLineBreaks.html_safe %>
If you're trying to display newlines saved from text areas, you could do the following in your view:
<%= simple_format from_textarea %>
No need to do manual substitution in this case.

What does it mean to add a hyphen to the closing tag of a ruby loop <% -%>

I'm a noob at this and can't figure out why the hyphen gets added to something like this:
Not even sure if my jargon in the title of this question is accurate.
adding the "-" will remove the line break for that line
It means simply:
Place any text (HTML) that follows <% -%> on the next line in the rendered template.
The hyphen is not necessary in the above code. Simply adding <% end %> is sufficient to execute the embedded ruby.
The use of hyphen is fully explained here and essentially effects rendered html. In your case, what the hyphen does is this:
1 Hyphen at the end of the tag, just the two spaces
2 before the tag on the line below will be left
3 <% -%>
4 Last line
The code will output with two spaces before " Last Line" just below your <% -%> tag
It means that it will add the \n (or maybe \r\n, I forget which) to the line.
It just effects way the HTML is formatted.
So if did:
>> helper.image_tag "image.jpg"
=> "<img alt=\"Image\" src=\"/images/image.jpg\" />"
it would output something like:
"<img alt=\"Image\" src=\"/images/image.jpg\" />\r\n"
Meaning that your html page would look like:
<image tag>
<whatever other tag>
instead of having them both on the same line.

Resources