Search code examples
ruby-on-railshaml

Multiline string in HAML


Because I don't want any of my lines to be wider than 80 columns, I want to split the last line into two lines. Adding a comma at the end of the line works as suggested here but then the comma appears inside the string. Is there a nice and clean way of doing this with HAML?

- if object.errors.any?
  %section.form_error_message
    %h4.form_error_message__title
      = "#{pluralize(object.errors.size, 'errors')} prevented this form from submitting. Please fix these errors and try again."

I want it all to be tucked inside 80 columns like they are on the left of this screenshot.

enter image description here


Solution

  • Haml has support for multiline sequences like this using the | character:

    - if object.errors.any?
      %section.form_error_message
        %h4.form_error_message__title
          = "#{pluralize(object.errors.size, 'errors')} prevented this form from |
            submitting. Please fix these errors and try again."                  |
    

    In this case you don’t really need this though, you can use interpolation directly in plain text, you don’t need the =:

    - if object.errors.any?
      %section.form_error_message
        %h4.form_error_message__title
          #{pluralize(object.errors.size, 'errors')} prevented this form from
          submitting. Please fix these errors and try again.
    

    (The output of this will be slightly different, as it will include the newline. You should’t notice that in the rendered HTML though, unless you are e.g. inside <pre> tags.)