In Rails - is there a rails method to convert newlines to br ?
Yes, rails has simple_format
which does exactly what you are looking for, and slightly better since it also adds paragraph tags. See
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Example:
simple_format(mystring)
Note that simple_format
allows basic HTML tags, but also passes text through sanitize
which removes all scripts, so it should be safe for user input.
How can I convert a newline to a BR tag?
str = str.gsub(/[\r\n]+/, "<br>")
This will turn any number of consecutive \r
and/or \n
characters into a single <br>
.
Rails: Converting a text field's linebreaks into br /
try
<%= simple_format @template.about %>
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
It works for me :-\
1.9.3p194 :017 > str = "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks?
1.9.3p194 :018"> \"I'll be the judge of that,\" he said!
1.9.3p194 :019"> And now, more useless copy so I can isolate that weird bud that Amanda found.
1.9.3p194 :020"> Wait! I meant 'weird bug..."
#=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n\"I'll be the judge of that,\" he said! \nAnd now, more useless copy so I can isolate that weird bud that Amanda found. \nWait! I meant 'weird bug..."
1.9.3p194 :021 > simple_format str
#=> "<p>Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n<br />\"I'll be the judge of that,\" he said! \n<br />And now, more useless copy so I can isolate that weird bud that Amanda found. \n<br />Wait! I meant 'weird bug...</p>"
or using gsub
1.9.3p194 :022 > str.gsub("\n", "<br />")
#=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? <br />\"I'll be the judge of that,\" he said! <br />And now, more useless copy so I can isolate that weird bud that Amanda found. <br />Wait! I meant 'weird bug..."
How to replace Space with Line Break in Ruby on Rails?
While printing it in html you will need to use raw
, otherwise rails will escape the tags
= raw name.gsub(" ", "<br>")
HTML and Ruby on Rails - Display br/ tags as line breaks, but other tags as strings
You could do something like this:
<% @user_input.split("<br/>").each do |line| %>
<%= line %><br/>
<% end %>
Output:
<a href='#2'>Go to #2</a>
<a href='#3'>Go to #3</a>
Or even better, use a regexp so you can split either <br>
or <br/>
:
<% @user_input.split(/<br\/>|<br>/).each do |line| %>
<%= line %><br/>
<% end %>
UPDATE
Some cases will fail with the above approach, for example:
<input type="text" value="<br/>">
To be able to handle those cases, you could use Nokogiri, already bundled with rails, but you'll need add a couple of additional steps in your code.
First, your controller:
def some_action
input = "<a href='#2'>Go to #2</a><br/><a href='#3'>Go to #3</a><br><input type='text' value='<br/>'>"
@user_input = Nokogiri::HTML.parse(input)
@user_input.search('br').each { |br| br.replace("\n") }
end
Basically, you will create a Nokogiri HTML document and replace all br
tags with "\n"
.
Second, create a css
class to use those "\n"
as break lines:
.new-lines {
white-space: pre-line
}
Now you will simply add this to your view:
<div class="new-lines">
<%= @user_input.css('body').children %>
<div>
Notice the use of class="new-lines"
, this is important to make each "\n"
act as a <br>
.
And the output:
<a href="#2">Go to #2</a>
<a href="#3">Go to #3</a>
<input type="text" value="<br/>">
Yes, there is a small caveat since the original value='<br>'
turned into value="<br/>"
, but i hope that not to be a big issue; but if it is, then you could do something like this:
<%= @input.css('body').children.to_s.gsub("<", "<").gsub(">", ">") %>
And the output:
<a href="#2">Go to #2</a>
<a href="#3">Go to #3</a>
<input type="text" value="<br/>">
You may need to enhance this code further for more edge cases, but i think this example will do the trick.
Also consider using a helper instead of throwing all the code in your controller/view.
Line break in string returned by a helper method
You should use <br>
or create it like tag('br')
:
your_string = "test string" + tag('br')
your_string.html_safe #return your string
As @max rightly pointed, from a security vulnerability (XSS) aspect you can use h()
on user-provided text, which converts your string to a safe string and allows you to securely call html_safe
on the full string.
Preserve newline in text area with Ruby on Rails
Newlines are actually being preserved(as \r\n
), you just don't see them in your index/show views.
In these views, call simple_format
on your post.body
field to replace \n
s with <br>
s(HTML newlines):
simple_format(post.body)
From docs:
simple_format(text, html_options = {}, options = {}) public
Returns text transformed into HTML using simple formatting rules.
Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped
in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is
appended. This method does not remove the newlines from the text.
Related Topics
How to Get the Current Time as 13-Digit Integer in Ruby
How to Make Ruby 1.9 the Default Ruby on Ubuntu
Problems with the Rails Console, Rvm and Readline
How Does Shovel (<<) Operator Work in Ruby Hashes
Thread Safety: Class Variables in Ruby
Ruby Hash Default Value Behavior
Why Does My Ruby 'Ri' Tool Not Return Results in Command Prompt
Ruby Source Code Analyzer (Something Like Pylint)
What Does 'Def Self.Function' Name Mean
How to Install Ruby 1.9.3 in MAC Os X Lion
Rails with Ruby-Debugger Throw 'Symbol Not Found: _Ruby_Current_Thread (Loaderror)'
I Have a Rails Task: Should I Use Script/Runner or Rake