简体   繁体   English

rails部分中的条件格式

[英]conditional formatting in rails partials

I am rendering a rails partial and I want to alternate the background color when it renders the partial. 我正在渲染部分轨道,我想在渲染部分时交替使用背景颜色。 I know that is not super clear so here is an example of what I want to do: 我知道这不是很清楚,所以这里是我想要做的一个例子:

Row One grey Background Row Two yellow background Row Three grey Background Row Four yellow background 行一灰色背景行两黄色背景行三灰色背景行四黄色背景
  • sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear 对不起stackoverflow接缝,以防止显示背景颜色,但我认为这使我的想法清楚

This is the view code that I am using 这是我正在使用的视图代码

<tr bgcolor="#AAAAAA">
  <td><%= row.name %></td>
</tr>

the _row.html.erb partial looks like this _row.html.erb部分看起来像这样

 <tr bgcolor="#AAAAAA"> <td><%= row.name %></td> </tr> 

The problem is I do not know how to change the background color for every other row. 问题是我不知道如何更改每隔一行的背景颜色。 Is there a way to do this? 有没有办法做到这一点?

You could use the Cycle helper. 你可以使用Cycle助手。 Something like this: 像这样的东西:

<tr class="<%= cycle("even", "odd") %>">
  <td><%= row.name %></td>
</tr>

Or in your case use bgcolor instead, although i would recomend using css classes. 或者在你的情况下使用bgcolor,虽然我会建议使用css类。

You can cycle through more than two values: cycle('first', 'second', 'third', 'and_more'). 您可以循环使用两个以上的值:cycle('first','second','third','and_more')。

There is also: reset_cycle('cycle_name') This makes sure that on each iteration, you will start again with your first value of the cycle list. 还有:reset_cycle('cycle_name')这确保在每次迭代时,您将再次使用循环列表的第一个值重新开始。

Check the rails documentation for more examples. 有关更多示例,请查看rails 文档

There is one "gotcha" with cycle: If you should append to the string, the cycle breaks. 循环中有一个“陷阱”:如果你应该附加到字符串,循环就会中断。 For example, 例如,

cycle('odd', 'even') << " some other classes"

will break the cycle. 会打破这个循环。 However, reversing the order or constructing a string works fine: 但是,反转顺序或构造字符串工作正常:

"some other classes " << cycle('odd', 'even')
"#{cycle('odd', 'even')} some other classes"

I've not (yet) delved into the source to see why this may be so. 我还没有深入研究消息来源,看看为什么会这样。 Also, I'm using Rails 3.2.x 另外,我正在使用Rails 3.2.x.

Another idea, you can use javascript to change the element's style based on (total number of TD's % 2). 另一个想法,你可以使用javascript来改变元素的样式(TD的%2的总数)。

That way all your visual stuff are contained in html/css/javascript layer. 这样你所有的视觉内容都包含在html / css / javascript层中。 Then again, this technique does not work if javascript is disabled. 然后,如果禁用javascript,此技术将不起作用。

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

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