简体   繁体   English

如何返回多个字符串,它们之间用空格隔开,在Rails中用Ruby分隔?

[英]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: 我正在使用application_helper.rb文件中定义的以下视图帮助器:

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 . 但是,这仅返回left_border ,而不返回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)%> 杀死多余的空间<%=even_odd(index)%>

and add quotes back to your class <td class="<%=even_odd(index) %>"> 并将报价添加回您的班级<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. 我不太熟悉erb模板,我在haml模板中习惯了这一点。 BTW I updated the answer. 顺便说一句,我更新了答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从单个字符串数组创建多个链接 Rails - Ruby - How to create multiple links from a single array of strings Rails - Ruby Lambda查询多个字符串(ruby on rails) - Lambda query multiple strings (ruby on rails) 如何在Rails上的ruby中使用select_tag返回多个参数 - How to return multiple parameters using select_tag in ruby on rails Ruby On Rails:如何在具有多个要渲染的变量值的 Rails 中的 &lt;%= %&gt; 标记内放置空间 - Ruby On Rails : How to Put Space Inside <%= %> tag in Rails With Multiple Variable Values To Render Ruby on Rails:在具有复杂业务逻辑的Rails应用程序中如何分离职责? - Ruby on rails: How are responsibilities separated in a rails application with complex business logic? 返回多个包含对象 Ruby on Rails JSON - Return multiple includes on object Ruby on Rails JSON 如何在Ruby on Rails中用换行符替换空间? - How to replace Space with Line Break in Ruby on Rails? 如何在Ruby on Rails中按格式转换字符串? - How to translate strings by format on Ruby on Rails? Ruby on rails - 如何检索连接字符串 - Ruby on rails - how to retrieve connection strings 如何在rails上的ruby中获取新的行分隔文本 - How to get new line separated text in ruby on rails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM