Reputation: 1090
I'm a newbie in scala. I am trying to build navigation tree like
I have a model class for it.
case class Field(id:Long, name:String, icon:String, parentid:Long)
object Field {
def all():List[Field] = {
List(
Field(1,"Parent1","1", 0),
Field(2,"Child1","2",1),
Field(3,"Child2","3",1),
Field(4,"Child3","4",1),
Field(5,"Child4","5",1)
)
}
}
And in my view I have a code for rendering:
@fields.groupBy(_.parentid).map { case ( parentid, tasks) =>
<ul>
<li>@parentid</li>
<ul>
@tasks.map { task =>
<li>@task.name</li>
}
</ul>
</ul>
}
But unfortunately the output is:
How to build navigation menu, where model has child/parent relationship? I hope you understand my question, and will help me. Sorry for my bad english
Upvotes: 2
Views: 511
Reputation: 1905
It would be quite tricky to convert the structure that you have to a tree. You would need to define another type to represent a tree node, and you would need a recursive function to process your list of Field
.
I suggest the following structure instead:
case class TreeNode(name: String, icon: String, children: TreeNode*)
object Menu {
val tree = TreeNode("parent", "0",
TreeNode("child1", "1"),
TreeNode("child2", "2"),
TreeNode("child3", "3",
TreeNode("grandchild1", "4"))
)
}
You will need a recursive function ("code block" in a template) to render it:
@renderNode(n: TreeNode) = {
<li>@n.name</li>
@if(!n.children.isEmpty) {
<ul>
@for(c <- n.children) {
@renderNode(c)
}
</ul>
}
}
<ul>
@renderNode(Menu.tree)
</ul>
I haven't tried recursive code blocks in a Play template, so I have no idea if this will work!
Upvotes: 1