Rails -- Add a line break into a text area - html

I got a rails app where I can input a few paragraphs of text into my model. The problem is I dont know how to input any line breaks.
I've tried to add " {ln}{/ln} ; {&nbsp} and {br}{/br}" but that only displays the html as text and no break.
Is there anyway I can set it so the text area control will use any of the html I place within the model entry?
Is there any thing I can type so rails will recognize, hey put a line here?

Line breaks in textareas are produced as `\n'. However, the problem is that if you simply dump it into your view, it will just be line breaks in your HTML source.
You can try using the Rails simple_format helper to take care of some of this for you: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M002285
It will auto-convert line breaks to HTML tags. You can use it with something like <%= simple_format(my_text_field) %>.

The problem isn't so much editing the value as it is rendering it later. To add newline characters to your value while editing it in a textarea, just hit the return key. When you re-edit that value later, the whitespace should still be there.
Rendering the whitespace is the tricky part. In HTML, whitespace is generally insignificant. A renderer like the one your browser uses will display a single space for any continuous string of whitespace. So merely dumping the value onto the page won't be enough:
<%= obj.description %>
Even though your value may be "One \t \n \n Two", it will show up on the screen as "One Two".
To get those new line characters to actually separate the lines when displayed, you'll need to convert them to HTML before rendering:
<%= obj.description.gsub(/\n/, '<br/>') %>
Of course, if users are entering data that will be included in your HTML, you should be escaping the values to protect against XSS. If new lines are the only thing you need to support, it should be as simple as this:
<%= h(obj.description).gsub(/\n/, '<br/>') %>
If you want to allow more complex formatting, look into Markdown and Textile (both of which Rails provides helper view methods for). Just be sure to investigate what if any support they provide for XSS prevention.

Keep user input unmodified and add this to your css:
white-space: pre-line;
It will display \r or \n (enter) in user input as a new line.

Here is another way to display the line breaks in a string while still escaping the rest of the text:
<%= safe_join(#object.textarea_input.split("\r\n"), "<br />".html_safe) %>

See here http://code.byteblues.com/2012/03/23/preloading-a-text-input-area-text_area-with-data-that-contains-a-line-break/
<%=raw text_area_tag :keywords, keywords, :rows => 8 %>

the problem with simple_format is that it's also adding other tags like <b><i><hr><h1>...
if you just want line breaks without other tags i suggest you build a partial (lets call it line_break):
<% text.split("\n").each do |t| %>
<%= t %><br>
<% end %>
then, just call it from your view:
<%= render partial: 'line_break', locals: {text: some_text} %>

What version of rails are you using?? Because the way to handle this, is different in rails 2 and 3.
Let's say the value of the record is "foo<br />bar"
In rails 3, if you want to evaluate the html, you could do <%=raw "foo<br />bar" %>, if you do so, you'll get a line break when you will see the view.
In rails 2 you don't have to do that, just do <%= "foo<br />bar" %>
Also, HTML doesn't get evaluated in a textarea anyway.

\n if memory serves (it hasn't been doing so well today... try at your own risk lol)
Edit: making the assumption you were talking about a textarea, if it is simple output, just use <br>

The answers above were good:
the gsub (#Ian) worked well
the simple_format (#Karl) was a bit over the top as #Aaron pointed out, wrapping everything in <p>
So I tweaked as follows:
simple_format(value, {}, wrapper_tag: 'div')

The other answers are wrong. Text area does not render as line breaks, because the innerHTML value of the TEXTAREA element does not render HTML..
You need to add the Line feed HTML entity:
EXAMPLE:
<textarea><%= "LINE 1
LINE 2
LINE 3".html_safe %></textarea>
See also New line in text area - Stack Overflow

If you are simply displaying your string in the view. then try it with
< p >This is my text< / p >< br />

Related

How to only make links html safe and ignore other html tags in Rails

I have a requirement where I need to make links clickable in text while keeping any other html tags as text (not html_safe). This means I cannot make the entire text html_safe as that will render the other html tags and I cannot sanitize the text and remove the other html tags. I've seen other websites handle this by making the html_safe links and other text on their own lines. It looks like the following when inspecting the html.
<span>
"This is an "
https://example.com/
"other <b>HTML</b>"
</span>
What would be the best way to do this in Rails 4?
When you call .html_safe on a string your actually getting an object that behaves like a string but is a ActiveSupport::SafeBuffer. When you append a string to a ActiveSupport::SafeBuffer its automatically escaped. Lets say you want to construct a span where the text is user input:
'<span>'.html_safe + text +'</span>'.html_safe
In this case we are safe against an XXS attack as the user originated text is automatically escaped:
irb(main):004:0> "<span>".html_safe + "<script>alert('You have been haxxored!')</script>" + "</span>".html_safe
=> "<span><script>alert('You have been haxxored')</script></span>"
That's what happens automatically when you output a variable in your views as the view is constructed as a ActiveSupport::SafeBuffer. Whenever you output a regular string it will be automatically escaped thus its secure by default.
Of course there is always going to be a huge number of programmers that just give proceed to give themselves a XSS vulnerability out of ignorance:
# WAAAH! Rails is escaping my tags! Bad rails!
'<span>'+ text +'</span>'.html_safe
Another way to approach the problem is to use the tag helpers, partials or Nokogiri instead of using string concatenation to construct HTML which in itself is tedious, borderline unreadible and error prone.
I was able to get this working using the following.
#module ApplicationHelper
def url_regexp
#url_regexp ||= %r{
(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)
(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|
[-A-Z0-9+&##\/%=~_|$?!:,.])*
(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|
[A-Z0-9+&##\/%=~_|$])
}ix
end
#in the view
<%- "This is a test https://example.com".partition(url_regexp).each do |text| %>
<%- if text =~ url_regexp %>
<%= "<a href='#{text}' target='_blank'>#{text}</a>".html_safe %>
<%- else %>
<%= text %>
<% end %>

How to convert spaces into tabs in ruby on rails correctly?

I'm converting linebreaks and extra spaces.
def simple_format_plus(string)
(h(string).gsub(/\n/, '<br/>').gsub(' ', "\t")).html_safe
end
In my views I'm calling:
<p><%= simple_format_plus(post.content) %></p>
However the html output doesn't show the "\t" part. I've even tried disabling the css, but the problem still persists. For some reason I can't display more than one space in succession.
There are 3 spaces instead of 1 in this line .
still displays as:
There are 3 spaces instead of 1 in this line .
If I inspect the <p> element the extra spaces show up in the developer console however, but not in the browser.
tab can't be interpreted in HTML. You can use &nbsp for three or the number of times you want. The helper method can be re-written like
def simple_format_plus(string)
(h(string).gsub(/\n/, '<br/>').gsub(' ', "&nbsp&nbsp&nbsp")).html_safe
end
Consecutive space characters are interpreted in HTML as a single space. If you want to display each space character as is in the source HTML file, then surround that part with <pre> ... </pre>.

Rails ignoring whitespace before <%= inserts

I like my view-source code to be nice an clean but any time I use <%= => tags the whitespace before that tag is ignored.
.html.erb:
View-Source:
Notice the Yield, crfs_meta, and stylesheet link tags ignore the whitespace before the tag. I am using standard 2 spaces as my "tab". For the Yield and when I render partials I can just compensate for the removed whitespace and put it in the partial, but I can't do that for the script and style sheet tags. Is there a way to make is keep my whitespace???
I just realized that the render tag for a layout and yield keeps the whitespace of the previous line (4 tabs, render is on 6 tabs) but inside that layout I have to put the first line at 0 tab, then the next line at 4 tabs, to get it inline at 6 tabs...
The problem isn't the <%= as your edit suggests. It's because the methods you call in your <%= ... %> block are generating more lines of output and those subsequent lines don't respect your indenting.
There's no really neat way to solve it as far as I can tell. You could replace any newlines in the output of those methods with the correct indenting but you are then trading of readability in your code for readability in your output.
For example, something like:
<%= csrf_meta_tags.gsub("\n", "\n ").html_safe %>
Or you could write a helper method (in application_helper.rb) to do it:
def indent_output(output, indentation = " ")
output.gsub("\n", "\n" + indentation).html_safe
end
And then your relevant view code is:
<%= indent_output(csrf_meta_tags, " ") %>
<%= indent_output(stylesheet_link_tag("bootstrap.min", "main"), " ") %>

Using ruby variables as html code

I would expect that the following:
<div style="padding-top:90px;"><%= u.one_line %></div>
simply pulls whatever is in u.one_line (which in my case is text from database), and puts it in the html file. The problem I'm having is that sometimes, u.one_line has text with formatted html in it (just line breaks). For example sometimes:
u.one_line is "This is < / b r > awesome"
and I would like the page to process the fact that there's a line break in there... I had to put it with spaces up ^^^ here because the browser would not display it otherwise on stackoverflow. But on my server it's typed correctly, unfortunately instead of the browser processing the line break, it prints out the "< / b r>" part...
I hope you guys understand what I mean :(?
always remember to use raw or html_safe for html output in rails because rails by default auto-escapes html content for protecting against XSS attacks.
for more see
When to use raw() and when to use .html_safe

How can i convert/replace every newline to '<br/>'?

set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
I tried this, content.gsub("\r\n","<br/>") but when I click the view/show button to see the contents of these line, I get the output/result=>
set tabstop=4<br/> set shiftwidth=4<br/> set nu<br/> set ai<br/> syntax on<br/> filetype plugin indent on
But I tried to get those lines as a seperate lines. But all become as a single line. Why?
How can I make all those lines with a html break (<br/>) ?
I tried this, that didn't work.
#addpost = Post.new params[:data]
#temptest = #addpost.content.html_safe
#addpost.content = #temptest
#logger.debug(#addpost)
#addpost.save
Also tried without saving into database. Tried only in view layer,<%= t.content.html_safe %> That didn't work too.
Got this from page source
vimrc file <br/>
2011-12-06<br/><br/>
set tabstop=4<br/><br/>set shiftwidth=4<br/><br/>set nu<br/><br/>set ai<br/><br/>syntax on<br/><br/>filetype plugin indent on<br/>
Edit
Delete
<br/><br/>
An alternative to convert every new lines to html tags <br> would be to use css to display the content as it was given :
.wrapped-text {
white-space: pre-wrap;
}
This will wrap the content on a new line, without altering its current form.
You need to use html_safe if you want to render embedded HTML:
<%= #the_string.html_safe %>
If it might be nil, raw(#the_string) won't throw an exception. I'm a bit ambivalent about raw; I almost never try to display a string that might be nil.
With Ruby On Rails 4.0.1 comes the simple_format from TextHelper. It will handle more tags than the OP requested, but will filter malicious tags from the content (sanitize).
simple_format(t.content)
Reference : http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html
http://www.ruby-doc.org/core-1.9.3/String.html
as it says there gsub expects regex and replacement
since "\n\r" is a string you can see in the docs:
if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\d' will match a backlash followed by ā€˜dā€™, instead of a digit.
so you are trying to match "\n\r", you probably want a character class containing \n or \r -[\n\r]
a = <<-EOL
set tabstop=4
set shiftwidth=4
set nu
set ai
syntax on
filetype plugin indent on
EOL
print a.gsub(/[\n\r]/,"<br/>\n");
I'm not sure I exactly follow the question - are you seeing the output as e.g. preformatted text, or does the source HTML have those tags? If the source HTML has those tags, they should appear on new lines, even if they aren't on line breaks in the source, right?
Anyway, I'm guessing you're dealing with automatic string escaping. Check out this other Stack Overflow question
Also, this: Katz talking about this feature