Multiline string in HAML

2019-05-24 20:23发布

问题:

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.

回答1:

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.)



回答2:

%div First line |
     and second line |

Will render:

<div>First line and second line</div>

If you don't even want a tag:

First line |
and second line |

Will produce:

First line and second line

You can use the command-tool haml, for instance copy the code then pbpaste | haml on macOS, or with a file cat file.haml | haml.