views:

26

answers:

2

I want to branch if a message-property-code does exist or not.

<g:if test="${message(code: 'default.code.foo')}">
  true
</g:if><g:else>
 false
</g:else>

should answer true if there a message property named default.code.foo and false if not.

It fails because it answers the code if there is no property for it.

+2  A: 

Then why don't you just test if the String returned is the code itself?

<g:if test="${message(code: 'default.code.foo') == 'default.code.foo'}">
  true
</g:if><g:else>
 false
</g:else>

If you need to do this in several places and want to make the code a bit more concise, then put this logic in a tag lib.

class MsgTagLib {
    static namespace = 'msg'

    def messageSource

    private static final NO_ARGS = [].toArray();

    def exists = {attrs ->

        try {
            messageSource.getMessage(attrs.code, NO_ARGS, Locale.default) 
            out << true
        } catch (NoSuchMessageException e) {
            out << false                
        }
    }
}

You could then call this in a GSP using:

<msg:exists code="default.code.foo"/>

Note

  1. The tag lib above is 100% untested, beware!
  2. The exists tag in it's form above doesn't support parameterized messages
Don
sometimes it is far to easy to see the solution... :) sure that solves it!
skurt
+2  A: 

Can't you supply a default that's a blank string?

<g:if test="${message(code: 'default.code.foo', default:'')}">
  true
</g:if><g:else>
 false
</g:else>

This will equate to false under Groovy's truth

tim_yates
+1 for cleverness
Don