How can I output a list of things in a template in Lift?
Let say for example that I have List[User] and I want to output it as a table. In Django, I would use a context variable "users" and iterate through it in the template like so:
//controller
user = User.objects.all()
context = {'users' : users}
return render_to_template('results.html', context}
//view
<table>
{% for user in users %}
<tr><td>{{user.name}}</td>
<td>{{user.email}}</td>
</tr>
{% endfor %}
</t开发者_高级运维able>
I appreciate any help.
PS: Could you also show me an example of the scala side - as I am clueless about how to approach this problem.
Template
<ul>
<lift:UserSnippet.showAll>
<li><foo:userName />: <foo:age /></li>
</lift:UserSnippet.showAll>
</ul>
Snippet Class
I'm assuming users
is a List[User]
.
import scala.xml.NodeSeq
import net.liftweb.util.Helpers
class UserSnippet {
def showAll(in: NodeSeq): NodeSeq = {
users.flatMap { user => Helpers.bind("foo", in, "userName" -> user.name, "age" -> user.age) }
}
}
See the lift wiki articles on designer friendly templates and snippets for more information.
if you're looking to use a pure java list, say an ArrayList from a seperate java call...you can do it this way....
Make sure to import the java conversions, and your java class file where your list is being created
(i'm assuming we have a list of "people" objects that is being returned from your java file, which would include a name, age, and sex properties)
//SCALA Code
import scala.collection.JavaConversions._
import my.java.package.something._
import scala.xml.NodeSeq
import net.liftweb.util.Helpers
class mySnippet {
//You want to run the ".toList" on your java list, this will convert it into a scala list
val myScalaList = my.java.package.something.buildMyList().toList
//This is the function that will bind the list to the html view
def displayPeople(html : NodeSeq) : NodeSeq = {
myScalaList.flatMap{person => bind("info", html,
"name", person.name,
"age", person.age,
"sex", person.sex)}
}
}
//HTML code
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
<lift:mySnippet.displayPeople>
<tr>
<td><info:name></info:name></td>
<td><info:age></info:age></td>
<td><info:sex></info:sex></td>
</tr>
</lift:mySnippet.displayPeople>
</table>
Hope this helps :)
-kevin
精彩评论