Tony K.
Tony K.

Reputation: 5605

In Lift, how do I select the top-level element in repeated (auto-duplicated) CssSel transform

I have the following html structure:

<div class="top_level">
   ... other elements ...
</div>

and I want the output to result in a sequence of DIV:

<div id="1" class="top_level">
   ... other elements ...
</div>
<div id="2" class="top_level">
   ... other elements ...
</div>
<div id="3" class="top_level">
   ... other elements ...
</div>

I am trying to do this via a CssSel transform where the nested elements themselves will be looped over (there is a table inside the div), so I have something akin to:

".top_level *" #> groups.map(group =>
  ".top_level [id]" #> group.id & // WHAT CSS Selector can I use? 
  ".the_row *" #> group.rows.map( ... )
  )

It all works fine, other than the ID does not get set. I can see that my selector ".top_level [id]" is nested, and therefore it makes sense that it doesn't work, but I cannot think of what else to put there to get the result I'm looking for.

Upvotes: 2

Views: 581

Answers (2)

Tony K.
Tony K.

Reputation: 5605

One other answer is to restructure the code as follows:

def listXform(itemTemplate : NodeSeq) : NodeSeq = {
  val iterableXform = for(t <- list;
      a <- t.optionalElement;
      b <- a.optionalElement
     ) yield {
     (".top_level [id]" #> a.id &
     // other bits
     ).apply(itemTemplate)
  }

  iterableXform.foldLeft(NodeSeq.Empty)( (a,b) => a ++ b)
}

def render(seq : NodeSeq) : NodeSeq = listXform(seq)

but in light of my earlier misunderstanding, this is less optimal.

Upvotes: 0

Dave Whittaker
Dave Whittaker

Reputation: 3102

Here is a way to repeat your .top_level element, while adding an id to each node and further processing the contents. You can cut and paste it into the REPL to play around with it.

scala> import net.liftweb.util.Helpers._
import net.liftweb.util.Helpers._

scala> val html = <div class="top_level">
     |   <table>
     |     <tr>
     |       <td>Cell</td>
     |     </tr>
     |   </table>
     | </div>
html: scala.xml.Elem = 
<div class="top_level">
  <table>
    <tr>
      <td>Cell</td>
    </tr>
  </table>
</div>


scala> val data = List(("id1", "cell 1"), ("id2", "cell 2"))
data: List[(java.lang.String, java.lang.String)] = List((id1,cell 1), (id2,cell 2))

scala> val sel = ".top_level" #> {
     |   data map { d =>
     |     ".top_level [id]" #> d._1 &
     |     "td *" #> d._2
     |   }
     | }
sel: net.liftweb.util.CssSel = CssBind(Full(.top_level), Full(ClassSelector(top_level,Empty))) 

scala> sel.apply(html)
res0: scala.xml.NodeSeq = 
NodeSeq(<div class="top_level" id="id1">
  <table>
    <tr>
      <td>cell 1</td>
    </tr>
  </table>
</div>, <div class="top_level" id="id2">
  <table>
    <tr>
      <td>cell 2</td>
    </tr>
  </table>
</div>)

Upvotes: 5

Related Questions