如何在HAML中处理多行Ruby参数?

25

我该如何在HAML中为一个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]

但是,当然前四行会产生语法错误。

5个回答

43

使用逗号将参数包裹起来

根据HAML FAQ

当函数有很多参数时,可以在多行上分解它,只要每一行都以逗号结尾即可。

因此,以下语句应该是有效的HAML代码:

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

12

您可以使用:ruby筛选器。

: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

查看这里的文档。

请注意,这是有意为之的,因为您不应该在模板中放置大量的Ruby代码。


我相信这也是正确的,所以我点了个赞,但我选择了CodeGnome的建议,因为它的语法不那么别扭。 - jhchen

2
%div= "First line " + |
      "and second line" |

将呈现:

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

您可以使用命令行工具 haml。例如,在MacOS中,复制代码后可以使用命令 pbpaste | haml 或使用文件 cat file.haml | haml

如果您甚至不想要标签:

First line |
and second line |

将产生:

First line and second line

0

这个有效:

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

请注意第一行和第二行后面的管道符号,以及管道符号前面的空格!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接