Simple way to use parameterised UI messages in Wicket?

There's a way, which although still involves creating a model, doesn't requires a bean with a getter.

given this message in a properties file:

msg=${} persons

Here's how to replace the placeholder with a value, be it a local variable, a field or a literal:

add(new Label("label", new StringResourceModel("msg", new Model<Serializable>(5))));

I think the most consistent WICKETY way could be accomplished by improving Jonik's answer with MessageFormat:

.properties:

msg=Saving record {0} with value {1}

.java:

add(new Label("label", MessageFormat.format(getString("msg"),obj1,obj2)));
//or
info(MessageFormat.format(getString("msg"),obj1,obj2));

Why I like it:

  • Clean, simple solution
  • Uses plain Java and nothing else
  • You can replace as many values as you want
  • Work with labels, info(), validation, etc.
  • It's not completely wickety but it is consistent with wicket so you may reuse these properties with StringResourceModel.

Notes:

if you want to use Models you simply need to create a simple model that override toString function of the model like this:

abstract class MyModel extends AbstractReadOnlyModel{
    @Override
    public String toString()
    {
        if(getObject()==null)return "";
        return getObject().toString();
    }
}

and pass it as MessageFormat argument.

I don't know why Wicket does not support Model in feedback message. but if it was supported there was no reason to use these solutions and you could use StringResourceModel everywhere.


Take a look at Example 4 in the StringResourceModel javadoc - you can pass a null model and explicit parameters:

add(new Label("message",
         new StringResourceModel(
             "msg", this, null, value)));

msg=Value is {0}