me-me
me-me

Reputation: 5809

Groovy shorthand if else operator

I'm trying to set a variable in a .gsp file with an object been passed to the view from the controller. 'item' is an object in this case with an attribute called 'sequence' So what I'm trying to do is set the var 'action' to the value of item.sequence and if item.sequence is null then set action value to the string "new".

<g:set var="action" value= "${item.sequence?item.sequence:'new'}"/>

Unfortunately, I'm getting the value of item.sequence and "new" together. Does anyone know how I can do this shorthand?

Upvotes: 3

Views: 16547

Answers (1)

allTwentyQuestions
allTwentyQuestions

Reputation: 1240

Sounds like a job for the Elvis Operator

value="${item.sequence ?: 'new'}"

This will return item.sequence as long as it is truthy. If item.sequence is falsy, then it will return the second expression.

Upvotes: 9

Related Questions