简体   繁体   中英

How to return multiple strings separated by a space in ruby on rails?

I am using the following view helper defined in my application_helper.rb file:

def even_odd(index)
  if index.to_i % 2 == 0
    "left_border white"
  else
    "left_border"
  end
end

In my view there is a table that needs alternate classes for a grey-white pattern:

<td class=<%= even_odd(index) %>> <%=investment.amount %> </td>

This, however, only returns left_border , but not left_border white . What am I doing wrong?

尝试这个

<td class="<%= even_odd(index)%>"> <%=investment.amount %> </td>

Rails具有此功能的内置帮助器:

<tr class="left_border <%= cycle(' white', '') %>"></tr>

try this

def even_odd(index)
 ((index.to_i % 2) == 0 ? "left_border white" : "left_border" )
end

kill the extra space <%=even_odd(index)%>

and add quotes back to your class <td class="<%=even_odd(index) %>">

I slightly updated your method, I used ternary operator to reduce line of codes :-

def even_odd(index)
  ((index.to_i%2 == 0) ? "left_border white" : "left_border")
end

and I also want to suggest you to use interpolation for helper methods in views :-

<td class="<%= even_odd(index) %>"> <%=investment.amount %> </td>

I am not much familiar with erb templates, I used to this in haml templates. BTW I updated the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM