2011-05-09 67 views
1

好的看一些播客我已经看到在Rails 3中,我们现在需要使用<%= %>标签。然而,只是把这个在我的application.html.erb文件中:升级到Rails 3:<%= if expression%>引发错误

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head></head> 
<body> 
    <%= if true %> 
true   
    <% end %> 
</body> 
</html> 

不会呈现'真正'如我所料。相反,我得到一个错误:

Showing /app/views/layouts/application.html.erb where line #5 raised: 

/app/views/layouts/application.html.erb:5: syntax error, unexpected ')', expecting keyword_then or ';' or '\n' 
    ');@output_buffer.append= (if true);@output_buffer.safe_concat(' 
            ^
/app/views/layouts/application.html.erb:7: syntax error, unexpected keyword_end, expecting ')' 
'); end 
     ^
/app/views/layouts/application.html.erb:10: syntax error, unexpected keyword_ensure, expecting ')' 
/app/views/layouts/application.html.erb:12: syntax error, unexpected keyword_end, expecting ')' 
Extracted source (around line #5): 

2: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
3: <head></head> 
4: <body> 
5: <%= if true %> 
6: true   
7: <% end %> 
8: </body> 

回到旧的<% %>标记修复了这个问题。它是否正确?铁路开发商是否决定切换回旧标签还是错过了一些东西?

rails -v打动了我:Rails 3.0.5

任何想法?

+0

这仅适用于像'form_for'一些标签。在这种情况下,您只需使用'<% if true %>'。 – Mischa 2011-05-09 07:51:22

+0

好吧,发布作为答案,我会将其标记为已接受。 – DJTripleThreat 2011-05-09 07:55:15

+0

试图解释为什么你必须使用'<%= %>'而不是'''form_for''<% %>'。 – Mischa 2011-05-09 08:00:10

回答

7

这只适用于一些标签。例如。 <% form_for ... %>成为<%= form_for ... %>。在这种情况下,您只需使用<% if true %>。原因是form_for生成输出,所以你使用<%= %>。一个简单的if语句不会生成输出,因此您使用<% %>。循环等也是如此:你只要继续使用<% %>即可。

据介绍here太:

form_for will insert form tags into the view around the content in the block, but there is no equals sign in the erb tags. This breaks the rule that erb blocks that output code to the view should use <%= %> and has made this difficult to work with the internals of form_for in previous versions of Rails. From [Rails version 3] onwards, however, we use an equals signs here as we would with any other erb code that generates output.

1
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head></head> 
<body> 
    <% if true %> 
true   
    <% end %> 
</body> 
</html>