2011-07-29 50 views
0

現在,我有我的看法任務模型DO循環:Rails 3 - 幫助查看,動態html attr?

<% @tasks.each do |t| %> 
    <div class="task purple"> 
    <%= link_to t.name, edit_task_path(t) %> 
    </div> 
<% end %> 

我需要一些幫助,使其成爲基於這樣把我的模型數據的div類的變化。我試過這樣做:

<% @tasks.each do |t| %> 
     <div class="task " + t.theme> 
     <%= link_to t.name, edit_task_path(t) %> 
     </div> 
    <% end %> 

但是,失敗悲慘。然後我閱讀了內容標籤,並嘗試瞭如下內容:

content_tag(:div, :class => t.theme){<%= link_to t.name, edit_task_path(t) %>} 

在循環中,但將其渲染爲文本。

無論如何,只需要一些幫助,學習如何根據模型數據更改html標籤屬性?這是我會建立一個視圖幫手嗎?

感謝

回答

2

你的第一種方法是不工作的原因,是你不包括僱員再培訓局標籤(<%= %>)輸出從t.theme的返回值。爲了,爲了在輸出顯示出來,你需要這樣做:

<% @tasks.each do |t| %> 
    <div class="task <%= t.theme%>"> 
    <%= link_to t.name, edit_task_path(t) %> 
    </div> 
<% end %> 

記住:ERb的一無所知HTML,它只是掃描<% %><%= %>標籤整個文件,並在評估Ruby代碼他們。

content tag應該work the way you've got it there,但我會在標籤中的內容作爲第三個參數,而通過使用塊,而不是(我假設你正在使用的Rails 3,語法略有不同在以前的版本):

<% @tasks.each do |t| %> 
    <%= content_tag :div, 
        :class => "task #{t.theme}", 
        link_to(t.name, edit_task_path(t)) %> 
<% end %> 
+0

啊,剛剛看到米哈伊爾更新了他的ERb答案。好吧。 – Jacob

2
<% @tasks.each do |t| %> 
    <div class="task <%= t.theme %>"> 
    <%= link_to t.name, edit_task_path(t) %> 
    </div> 
<% end %> 
+0

你忘了'<%= %>'''任務#{t.theme}「' – rubish

+0

yeap,謝謝你們,用haml太長:) –