Rails: Realize nl2br in PHP


Here’s the code to realise nl2br of PHP in Rails.

Environment

(Unless Rails changes considerably), it can be used in most versions.

  • Rails 4.2.5
  • Ruby 2.0.0

Method 1: User Prepared Function

Rails method simple_format helps you. But it’s somehow different from nl2br.

simple_format

This function find 2 successive LF (\n) and divide string to paragraphs with them, and convert non-successive LF to <br>.

It creates not only br tag, also p tag. The tag to be used to make paragraph is p tag as default, and you can change it with option parameter :wrapper_tag, but can’t ignore paragraph sectioning.

Method 2: Create Custom Function

For example, create the function nl2br at ApplicationHelper like the following.

It doesn’t realize all of nl2br in PHP but it convert LF to <br>. We can use it as the following.