Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 i18n how to *not* escape newlines

I'm using i18n in my .text.haml mailer templates and I want to have a string in en.yml that has a newline but t() is always escaping them even if I use html_safe or suffix the key name with _html.

Is there a way to do this??

p3_html: >
    You love monkeys:
     \n- You look like one
     \n- Your smell like one
     \n- Your account has been flagged

In my html.haml template:

!= t('emails.post.twitter_forbidden.p3_html').html_safe

No matter what the \n are escaped. I can't use %br or anything else because these are text templates. I know I could split this into 4 i18n strings but that would be really sad.

BTW, I checked and it is i18n escaping, not haml.

like image 531
eagspoo Avatar asked Jun 27 '12 20:06

eagspoo


2 Answers

You could do something like this:

t('emails.post.twitter_forbidden.p3_html').html_safe.gsub("\n", '<br/>')

As far as I know, this is the only way.

Edit

Actually, after some digging, I found the simple_format helper.

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

like image 85
Chuck Callebs Avatar answered Sep 28 '22 08:09

Chuck Callebs


Couple of options here: As mentioned above, simple_format will help. Format your yml file like so:

    p3_html: |
      Some text:
      - Point 1
      - Point 2
      - Point 3

And then use

   =simple_format t(:p3_html)

This will give you something like

    <p>Some text
      <br>
      - Point 1
      <br>
      - Point 2
      <br>
      - Point 3
    </p>

Or if you want each line a new paragraph:

    p3_html: |
      Some text:

      - Point 1

      - Point 2

      - Point 3

Which should give you this:

    <p>Some text</p>
    <p>- Point 1</p>
    <p>- Point 2</p>
    <p>- Point 3</p>

or something like this is more flexible

    <% t(:p3_html).each_line do |line| %>
      <li>= |line|</li>
    <% end %>

Enables you to put in different formatting:

    <li>- Point 1</li>
    <li>- Point 2</li>
    <li>- Point 3</li>

Final option is to use an array in yaml:

      p3_html: 
        - Some text:
        - - Point 1
        - - Point 2
        - - Point 3

    <% t(:p3_html).each do |line| %>
      <p>= |line|</p>
    <% end %>

Possibly cleaner, though I think it will play merry hell with commas, and the advantage to the above version is that you can switch between formats without needing to modify your yaml

like image 21
Carpela Avatar answered Sep 28 '22 08:09

Carpela