2013-06-03 38 views
1

在我的profile.html.erb文件中,當我嘗試將一個類或id分配給erb時,出現語法錯誤。下面是一個例子:語法錯誤,意外的',',期待tCOLON2或'['或'。'當分配一個類到erb

<p>"<%= current_user.current_program.name, :id => 'progress' %>" Progress</p> 

這給了我下面的錯誤:

SyntaxError in Users#profile 

Showing /.../app/views/users/profile.html.erb where line #13 raised: 

/Users/.../app/views/users/profile.html.erb:13: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.' 
...er.current_program.name, :id => 'progress');@output_buffer.... 
...        ^

我想不通的語法錯誤是什麼。我完全被難住了。

+1

僅供參考:Erb不知道'類'或'id'。它只知道'<% … %>'運行Ruby代碼,'<%= … %>'運行Ruby代碼,在結果上調用'to_s'並將該字符串粘在那個點上。如果你想生成支持HTML的內容,你必須使用Rails助手。 – Phrogz

回答

4

我們可以重現和簡化您的問題在一個獨立的Ruby,像這樣:

require 'erb' 
ERB.new("<p><%= name, :a => 'b' %></p>").run 

產生錯誤:

SyntaxError: (erb):1: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.' 
..."; _erbout.concat((name, :a => 'b').to_s); _erbout.concat ... 
...        ^
    from /Users/phrogz/.../ruby/1.9.1/erb.rb:838:in `eval' 
    from /Users/phrogz/.../ruby/1.9.1/erb.rb:838:in `result' 
    from /Users/phrogz/.../ruby/1.9.1/erb.rb:820:in `run' 
    from (irb):2 
    from /Users/phrogz/.../bin/irb:16:in `<main>' 

更簡單,同時ERB出來混的:

a, :b=>'c' 
#=> SyntaxError: (irb):3: syntax error, unexpected tASSOC, expecting tCOLON2 or '[' or '.' 

你剛纔的是無效的Ruby代碼。你想在那裏做什麼?將:id => 'progress'散列作爲參數傳遞給.name方法?如果是這樣,然後刪除逗號,和(可選),包括爲清楚起見括號:

<p>"<%= current_user.current_program.name(:id=>'progress') %>" Progress</p> 

如果你正在使用Ruby 1.9+,你可以使用簡單的散列與非符號鍵語法:

<p>"<%= current_user.current_program.name(id:'progress') %>" Progress</p> 

然而,似乎不太可能對我來說,name方法需要這樣的哈希值,所以我再問:什麼是你真正想要實現? name方法返回什麼,以及你想要什麼HTML輸出?


以一個猜測,也許你希望通過.name返回的文本將在<span id="progress">包裹?如果是的話,你必須這樣做,如:

<p>"<span id="progress"><%= current_user.current_program.name%></span>" Progress</p> 

或者可能使用content_tag

<p><%= content_tag("span", current_user.current_program.name, id:'progress') %> Progress</p> 

在Haml的,這將是:

%p 
    %span#progress= current_user.current_program.name 
    Progress 
+0

謝謝!很好的答案。我試圖爲current_user.current_program.name生成的單詞指定一個類,並認爲我可以將它分配給:id =>'progress'。感謝您的解釋! – Arel

+0

FWIW我強烈建議[Haml](http://haml.info)超過Erb。它不那麼打字,而且更整潔。 – Phrogz

+1

因此,爲了分配一個類,你希望'class:...'而不是'id:...',對嗎? – Phrogz

0

也許如果您刪除逗號,將工作(是current_user.current_program.name一種以散列作爲參數的方法?)

相關問題