25

How can I use multiple lines for a single Ruby statement in HAML? For example, I'd like to write something like the following:

- entries = [{
-   :title => "The Fellowship of the Ring", 
-   :body => "We should walk instead of fly"
- }]

!!! 5
%html
  %head
    %title Blog
  %body
    #content
      - entries.each do |entry|
        .entry
          %h3.title= entry[:title]
          %p.body= entry[:body]

But of course the first four lines produce a syntax error.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
jhchen
  • 14,355
  • 14
  • 63
  • 91

5 Answers5

43

Wrap Arguments with Commas

According to the HAML FAQ:

[W]hen a function has lots of arguments, it’s possible to wrap it across multiple lines as long as each line ends in a comma.

So, the following should be valid HAML:

- entries = [{ :title => "The Fellowship of the Ring", 
               :body  => "We should walk instead of fly" }]
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
12

You can use :ruby filter.

:ruby
  entries = [{ 
    :title => "The Fellowship of the Ring", 
    :body  => "We should walk instead of fly" 
  }]

!!! 5
%html
  %head
    %title Blog
  %body
    #content
      - entries.each do |entry|
        .entry
          %h3.title= entry[:title]
          %p.body= entry[:body]
7

Check out the docs here.

Note that it's intentionally awkward because you're not supposed to be putting lots of ruby in your templates.

Luke
  • 4,855
  • 1
  • 22
  • 18
  • I believe this is also correct so I gave an upvote but I went with CodeGnome's suggestion since it's less awkward syntax. – jhchen Mar 25 '13 at 22:41
2
%div= "First line " + |
      "and second line" |

Will render:

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

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.

If you don't even want a tag:

First line |
and second line |

Will produce:

First line and second line
Dorian
  • 22,759
  • 8
  • 120
  • 116
0

This works:

= link_to( |
  'Delete', |
  attachment_path(attachment),
  confirm: 'Are you sure?',
  method: :delete,
  remote: true,
  )

Note the pipes after both the first and second lines, and a space before the pipes!