【问题标题】:What function is meant to format/substitute {0} {1} parameters in an string in Grails/Groovy?什么函数用于格式化/替换 Grails/Groovy 中字符串中的 {0} {1} 参数?
【发布时间】:2009-08-06 08:31:44
【问题描述】:

我刚刚开始使用 Groovy/Grails

我注意到您在验证表单时收到的错误消息如下所示:

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

例如此代码将错误转储到控制台

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

现在,it.arguments 包含了这里需要填写的参数。

问题是,我在 Grails 或 Groovy 文档中找不到任何方法可以根据 {0}、{1} 等位置参数格式化字符串并替换数组中的值

我需要类似 python 的 %

格式化这些错误字符串以便正确替换参数的正确方法是什么?

【问题讨论】:

    标签: string grails formatting groovy


    【解决方案1】:

    这些标记实际上是使用标准 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"))
    

    【讨论】:

    • 谢谢!这对于 Groovy/Grails 来说是一个大问题:如果您没有使用 Java 的经验(由于哲学/政治原因,我多年来一直避免使用 Java),至少在查看 Grails/Groovy 时,有些事情会难倒您文档....
    【解决方案2】:

    看看 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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多