Ruby on rails If语句中额外的Ruby行会导致Haml中出现问题吗?
我试图在我的一个Haml视图中的If/Else语句中添加一些(未呈现的)注释,但这似乎会引起问题 我想要以下代码:Ruby on rails If语句中额外的Ruby行会导致Haml中出现问题吗?,ruby-on-rails,ruby,haml,Ruby On Rails,Ruby,Haml,我试图在我的一个Haml视图中的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" wi
- # 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问题,如果我提出的不恰当,请告诉我。
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)
如果你试着在注释之前把注释缩进更深一点,会发生什么呢?这很有道理。非常感谢!真棒的解释。。。喜欢就好了:))