How to correctly have multi line yaml strings?

11,610

Solution 1

Ugh.. after digging more on different keywords I found that

  = simple_format(t("mailer.beta_welcome.intro"))

does the trick although this seems stupid i see no workaround for now

Solution 2

Your first example works fine

foo.yml

intro: |
  We are happy that you are interested in
  and  
  more

foo.rb

require 'yaml'
puts YAML.load_file('foo.yml').inspect

Output

{"intro"=>"We are happy that you are interested in\nand  \nmore\n"}

Solution 3

Late answer for Googlers:

It looks like you were trying to output it as HTML, which means it was indeed outputting the newlines if you were to inspect the page. HTML largely ignores whitespace, however, so your newlines and spaces were being converted into just a space by the HTML renderer.

According to the simple_format docs, simple_format applies a few simple formatting rules to text output in order to render it closer to what the plaintext output would be - significantly, it converts newlines to <br/> tags.

So your problem had nothing to do with YAML, which was performing as expected. It was actually because of how HTML works, which is also as expected. simple_format fixed it because it took your string from YAML with newlines and converted it to a string with <br/> tags so that the newlines actually showed up in the HTML, which is what you wanted in the first place.

Share:
11,610
Rubytastic
Author by

Rubytastic

Just a coder!

Updated on June 08, 2022

Comments

  • Rubytastic
    Rubytastic almost 2 years

    newlines on multiple lines does not seem to work out for me:

    Something like:

      intro: |
        We are happy that you are interested in
        and  
        more
    

    and + more needs to be on a newline but it fails.

      intro: |
        | We are happy that you are interested in
        | and  
        | more
    

    or

      intro: |
        We are happy that you are interested in \n
        and  
        more <2 spaces >
        another one
    

    All fail.

    How to correctly have multiline in a yaml text block?

    I use this in HAML view in rails app like

    = t("mailer.beta_welcome.intro")

    But no newlines are printed this way, do i need to output it differently with raw or something?

  • Rubytastic
    Rubytastic over 10 years
    hmm it does not work for me :S. I try to put email content into locale to use in haml like = t("mailer.beta_welcome.intro") it does not print the newlines
  • cincodenada
    cincodenada almost 10 years
    See my answer: this isn't a stupid trick, it's just misunderstanding how HTML works.