【问题标题】:Extra Ruby lines inside If statements cause problems in Haml?If 语句中的额外 Ruby 行会导致 Haml 出现问题?
【发布时间】:2013-06-23 20:01:35
【问题描述】:

我试图在我的一个 Haml 视图中将一些(未渲染的)cmets 放入 If/Else 语句中,但这似乎会导致问题。

我想要以下代码:

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

- # Stuff like _____ activates the else statement
- else
  (Some other code)

不幸的是,Rails 向我抛出了这个错误:

Got "else" with no preceding "if"

如果我删除“else”评论,即

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

- else
  (Some other code)

一切都按预期进行。问题不在于评论本身。我必须删除实际的 Ruby 代码行(包括连字符)才能使其呈现。也就是说,即使我只是在一个连字符前面留下一个空行,就像这样:

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

-
- else
  (Some other code)

我得到同样的错误。其他可能相关的细节:稍后有更多代码与 if/else 语句处于相同的缩进级别(不在其中),并且整个内容嵌套在表单中。有人可以向我解释发生了什么问题吗?非常感谢!

附:这是我的第一个 SO 问题,所以如果我提出不当,请告诉我。

【问题讨论】:

  • 如果您尝试在 else 之前更深地缩进评论会发生什么?

标签: ruby-on-rails ruby haml


【解决方案1】:

HAML reference says:

Ruby 块,就像 XHTML 标记一样,不需要在 Haml 中显式关闭。相反,它们会根据缩进自动关闭。每当在 Ruby 求值命令后缩进增加时,一个块就开始了。它在缩进减少时结束(只要它不是 else 子句或类似的东西)。

因此,当您减少缩进,并且该行不是 else 子句(或类似的,例如 elsif)时,if 完成 - 隐式添加 end。那么else 行当然是无效的

您的解决方案是在 else 子句之前或之后缩进注释:

- if @condition
  - # Stuff like ______ activates the if statement
  (Some code)

- else
  - # Stuff like _____ activates the else statement
  (Some other code)

【讨论】:

  • 这很有意义。非常感谢!
  • 很棒的解释...喜欢它:))
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2017-09-27
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多