Simple way to use parameterised UI messages in Wicket?

后端 未结 6 642
借酒劲吻你
借酒劲吻你 2021-01-02 02:43

Wicket has a flexible internationalisation system that supports parameterising UI messages in many ways. There are examples e.g. in StringResourceModel javadocs, such as thi

6条回答
  •  独厮守ぢ
    2021-01-02 03:25

    Creating a Model for your Label really is The Wicket Way. That said, you can make it easy on yourself with the occasional utility function. Here's one I use:

    /**
     * Creates a resource-based label with fixed arguments that will never change. Arguments are wrapped inside of a
     * ConvertingModel to provide for automatic conversion and translation, if applicable.
     * 
     * @param The component id
     * @param resourceKey The StringResourceModel resource key to use
     * @param component The component from which the resourceKey should be resolved
     * @param args The values to use for StringResourceModel property substitutions ({0}, {1}, ...).
     * @return the new static label
     */
    public static Label staticResourceLabel(String id, String resourceKey, Component component, Serializable... args) {
        @SuppressWarnings("unchecked")
        ConvertingModel[] models = new ConvertingModel[args.length];
        for ( int i = 0; i < args.length; i++ ) {
            models[i] = new ConvertingModel( new Model( args[i] ), component );
        }
        return new CustomLabel( id, new StringResourceModel( resourceKey, component, null, models ) );
    }
    

    Details I'm glossing over here are:

    1. I've created my own ConvertingModel which will automatically convert objects to their String representation based on the IConverters available to the given component
    2. I've created my own CustomLabel that applies custom label text post-processing (as detailed in this answer)

    With a custom IConverter for, say, a Temperature object, you could have something like:

    Properties key:
    temperature=The current temperature is ${0}.
    
    Page.java code:
    // Simpler version of method where wicket:id and resourceKey are the same
    add( staticResourceLabel( "temperature", new Temperature(5, CELSIUS) ) );
    
    Page.html:
    The current temperature is 5 degrees Celsius.
    

    The downside to this approach is that you no longer have direct access to the Label class, you can't subclass it to override isVisible() or things like that. But for my purposes it works 99% of the time.

提交回复
热议问题