Reputation: 13811
Lets say I have a map like this ( which is returning from a controller)
a= [a:[1,2,3,4],b:[5,6,7,8],c:[9,10]]
[a] //returning [a] from controller to the view
Now in Grails view, how should I render them so that they look something like this in my browser :
a
-- 1
-- 2
-- 3
-- 4
b
-- 5
-- 6
-- 7
-- 8
//so on..
I did something like this on a particular case of displaying the details(with hint got from the answer given by Antoine) :
<html>
<head>
<title>
All Tasks.
</title>
<meta name ="layout" content="main" />
</head>
<body>
<h2>All the task</h2>
<g:each in="${tasksByDate}" var ="tasks">
<h4>${tasks.key}</h4>
<g:each in="${tasksByDate.value}" var="content" >
<div id = "todayswork">
${content}
</div>
<hr/>
</g:each>
<br />
</g:each>
</body>
</html>
But when I render it in my browser, I'm getting only the heading in my browser. Like this :
All the task
//other contents missing. . .
And I'm sure that from the controller alltasks
the value is passing to the view, with the name tasksByDate
. As it is printing it on my console like this :
[2011-12-19 14:21:35.949:[Belongs to Schedule Finish task A], 2011-12-21 14:21:35.897:[Belongs to Schedule Finish task A], 2011-12-23 14:21:35.907:[Belongs to Schedule Finish task A], 2011-12-19 14:21:36.051:[Belongs to Schedule Finish task A], 2011-12-17 14:21:36.048:[Belongs to Schedule Finish task A]]
Here is my controller code :
def alltasks = {
def allTasks = DaySchedule.findAllByTaskIsNotNull()
def tasksByDate = [:]
tasksByDate.putAll(
allTasks.groupBy {
it.Todaysdate
}
)
println tasksByDate
[tasksByDate]
}
Where I'm making mistake?
Thanks in advance.
Upvotes: 2
Views: 10026
Reputation: 6828
In your controller, replace the last line of the allTasks action :
[tasksByDate]
... by ...
[tasksByDate : tasksByDate]
The return of a controller action (as far as I know) should be a map, not a list. The key is the name of the variable that you will retrieve in the GSP, the value is the contents of that variable.
See http://grails.org/doc/latest/guide/single.html#controllers, chapter 6.1.3 Models and Views
Upvotes: 1
Reputation: 5198
You can iterate over a map elements using g:each
. The key method of a map element will return the key (a, b, c in your example) and the value
method will return the associated value (in your case, a list of integers). In turn you can use g:each
on this list.
Here is what I would do in GSP:
<ul>
<g:each var="mapElement" in="${a}">
<li>$mapElement.key
<ul>
<g:each in="${mapElement.value}" var="number">
<li>$number</li>
</g:each>
</ul>
</li>
</g:each>
</ul>
Based on your formatting I deduced that you want to present your map as a list of lists, hence the nested <ul>
elements.
Upvotes: 9