开发者

Line breaks not displaying in view

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜