What function is designed to format / replace {0} {1} parameters in a string in Grails / Groovy?

I am just starting with Groovy / Grails

I noticed that the error messages you get when validating the form look like this:

Property [{0}] of class [{1}] cannot be blank

For example, this code for uploading errors to the console

        s.errors.allErrors.each
        {
            println it.defaultMessage
        }

Now it.arguments contains the arguments that you need to fill out here.

The problem is that I cannot find any method in the Grails or Groovy documentation that formats strings based on positional parameters like {0}, {1} and replaces values ​​from an array

I need something like python%

What is the correct way to format these error strings so that the parameters are correctly replaced?

+5
2

java.text.MessageFormat API. Grail g: message, , args = "...":

<g:message code="mymessagecode" args="${['size', 'org.example.Something']}"/>

( GSP IIRC) :

g.message(code:'mymessagecode',args: ['size', 'org.example.Something'])

, , , . ( "" ) Spring.

, API- . . :

import java.text.MessageFormat

...

args = ["english"].toArray()
println(MessageFormat.format("Translation into {0}", args))

// Or - as the method is variadic:
println(MessageFormat.format("Translation into {0}", "english"))
+8

, Groovy, .

MessagesBundle_en_US.properties:

   greetings = Hello {0}.
   inquiry = {0}: How are you {1}? 
   farewell = Goodbye.

ResourceBundleWithSugar.groovy:

    import java.text.MessageFormat
    class ResourceBundleUtils {
      def propertyMissing(String name) { this.getString(name) }
      def methodMissing(String name, args) {
        MessageFormat.format(this.getString(name), args)
      }
    }
    ResourceBundle.metaClass.mixin ResourceBundleUtils

    def msg = ResourceBundle.getBundle("MessagesBundle", new Locale("en","US"));
    println msg.greetings("Serge")
    println msg.inquiry("Serge","Mary")
    println msg.farewell // You can use also: msg.['farewell'] msg."farewell" or msg.getString("farewell")

:

    Hello Serge.
    Serge: How are you Mary?
    Goodbye.
0

All Articles