Reputation: 6625
I have a grails object that I want to extract the first value in it. I'm new to grails and not understanding the language fully yet. I used a loop to extract them before but this time I just need the first value and nothing else. I tried just using
<div id="blaa">${items}[0].value"</div>
That threw an error.
Below is usually how I would loop through the object.
<g:each in="${items}" var="item" status="i">
<li><a href="#">${item.value}</a></li>
</g:each>
Upvotes: 2
Views: 1257
Reputation: 31280
While @Gregg's answer is correct and will allow you to get the first element, there is an easier way and it's very close to what you tried:
<div id="blaa">${items[0].value}"</div>
The issue is that you need to have all of your "code" pieces within the ${...}
structure. Everything outside of that is just treated as a string.
As long as items
is an ordered Collection
(so, a List
, a Map
, or a Range
, but not a Set
), you can access it like an array in Groovy (the language Grails is built in). @Gregg's answer explicitly converts items
to an array first and then accesses it like an array.
Upvotes: 2
Reputation: 35864
Making some assumptions here because you're not showing a lot of code and you also didn't tell us the error:
By default collections in Grails are Sets. To get the first value in a set you could do something like:
${item.toArray()[0]}
Upvotes: 1