16

Im new to grails (1.3.7) and Im trying to get something to work:

In my controller, I give back a few lists which I want to access in my gsp. Accessing works, but I only want to access them if they are not empty. The check if a list is empty or not does not work.

Here is what my controller gives back:

return new ModelAndView("/questions/questions", [ questionsList101 : allQuestions101, questionsList102 : allQuestions102, ... ])

allQuestions-objects are "def allQuestions.." containing Questions-Objects (Database-Object)

on my gsp now I try the following:

<g:if test="${!empty questionsList101}">  101:<br/>
<g:each in="${questionsList101}" var="elem" status="i">
  <g:checkBox name="${questionsList101[i].id}" value="${questionsList101[i].id}"/>${questionsList101[i].id}<br/>
</g:each>
<br/>
</g:if>

the loop is working, the check for emptiness is not. I tried with "not empty", "!empty", ... dont know whats wrong! any help is apreciated! :-)

nano7
  • 2,455
  • 7
  • 35
  • 52

2 Answers2

37

The "grooviest" way to do this is

<g:if test="${questionList101}">

In Groovy, null objects and empty Collections are coerced to false. See the documentation on Groovy truth here: http://groovy-lang.org/semantics.html#Groovy-Truth

Matt Lachman
  • 4,541
  • 3
  • 30
  • 40
16

In GSPs, you have full groovy support in a ${} expression. You can do proper method calls on your objects if you want. Try this:

<g:if test="${questionsList101 != null && !questionsList101.isEmpty()}">
Jon Quarfoth
  • 2,129
  • 16
  • 20
  • I tried the first, it only worked for lists which are not empty - funny. Otherwise I get this error message: Error processing GroovyPageView: Error executing tag : Cannot invoke method isEmpty() on null object :-) The same for the other method. I cant invoke them if the object is null - very funny.... – nano7 Jun 23 '11 at 14:31
  • Looks like you just need a null check then. I'll update my answer. – Jon Quarfoth Jun 23 '11 at 14:35
  • 2
    Umm, if you're using Grails, how about a Groovy way to write that? ${! questionsList101?.isEmpty()} (note the nullchecking ?) – billjamesdev Jun 23 '11 at 15:49
  • Thanks. I knew there was a better way, but I had a bit of a brain lapse there and figured I'd just get him something that worked quickly. – Jon Quarfoth Jun 23 '11 at 16:04
  • 1
    Upon further investigation however, ${! questionsList101?.isEmpty()} doesn't seem to handle the null case. I'm going to put it back to the less-groovy way for now... – Jon Quarfoth Jun 23 '11 at 16:35