1

I was wondering, does Lift have an iteration tag (ex: for, foreach)? When I was working with JSP, i could easily iterate a List, just with JSP, passing the object to the tag. Something like this, or like this. I know it's not really the best example, but you do understand my intentions. To sum up, does this exist with Lift, or if not, how would I manage to do such thing?

The last thing i want to do is hardcode html.

1 Answer 1

10

In short: No. Lift’s design strictly separates logic from design and as such forbids the use of generalised tags in the template markup.

Have a look at the view first article in order to see how lift can handle iterations.

An example from the article: Your markup:

<table>
  <lift:show.users>
    <tr>
      <td><f:first_name>David</f:first_name></td>
      <td><f:last_name>Pollak</f:last_name></td>
    </tr>
  </lift:show.users>
</table>

Your code:

class Show {
  def users(xhtml: NodeSeq): NodeSeq = 
    Users.findAll.flatMap(user => 
      bind("f", xhtml, 
        "first_name" -> user.firstName, 
        "last_name" -> user.nameName
      )
    )
}

Now, what lift does when it sees the tag <lift:show.users> is calling the corresponding method with the tag’s content as the argument. The tag will then be replaced by the return value of the users method.

The users method does the iteration over all Users and for each user, it binds the values of first and second name to the inner xhtml. All those iterations are then concatenated (through flatMap) and returned.

When I started with lift, I’d always found this approach a little too rigid; having a tiny loop here and there, how could that possibly hurt? But now that I know how easy it is to call and create your own snippets from the template code, I cannot imagine using anything like jsp anymore. It is weak in comparison and clutters your markup. And of course, you lose much of Scala’s power of validation.

Notes:

The reason the template tags are filled with content is for designing purposes. In this case the dummy tags and values are going to be replaced during the bind. The template designers can thus fill the tags with more or less meaningful content which allows the coder to better understand the semantics the designer had in mind.

4
  • Why is "David" and "Pollack" in there? Nov 29, 2010 at 19:00
  • Because it’s copied from the Lift wiki.
    – Debilski
    Nov 29, 2010 at 20:26
  • Will it print out his name for each user? Nov 29, 2010 at 20:37
  • No, when it iterates over Users it will bind user.firstName to <f:first_name>David</f:first_name> and replace tag plus content with the plain name of the real user. One could also preserve the content, though.
    – Debilski
    Nov 29, 2010 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.