scala: Adding attributes (odd and even rows) to xml table
- by Debilski
In a Lift application, I’d like to add a special tag which takes the <tbody> part of the next table and adds odd and even classes (for example) to each <tr> tag. Alternating, of course. While I have found a way to add another attribute to all <tr> tags, there are still a few problems left (see code below).
First, it doesn’t work. cycle.next is called too often, so in the end, everything is an odd row. Other problems are that the code doesn’t exclude inner tables (so a nested <tr> would be transformed as well) and that it also affects the <thead> part of the table.
Ideas to make this code work? (Of course, if there already is a lift-based solution – without jQuery – for this, I’ll gratefully take it.)
class Loop(val strs: String*) {
val stream_iter = Stream.continually(strs.toStream).flatten.iterator
def next = stream_iter.next
}
val cycle = new Loop("even", "odd")
val rr = new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case elem : Elem => elem match {
case Elem(_, "tr", att @ _, _, _*) =>
elem % Attribute(None, "class", Text(
List(att.get("class").getOrElse("").toString, cycle.next).reduceLeft(_+" "+_).trim
), Null) toSeq
case other => other
}
case other => other
}
}
val rt = new RuleTransformer(rr)
val code = <table>
<thead><tr><td>Don’t</td><td>transform this</td></tr></thead>
<tbody>
<tr class="otherclass">
<td>r1c1</td><td>r1c2</td>
</tr>
<tr>
<td>r2c1</td><td>r2c2</td>
</tr>
<tr>
<td>r3c1</td><td>r3c2</td>
</tr>
</tbody>
</table>
println(rt(code))