Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Parameterized MessageFormat with non-Value attributes of JSF components

Tags:

jsf

jsf-2

I have use case in which I have to use resource bundle to display various texts on UI. Some of these resource bundle entries take paramets (e.g. {0}), for these I use h:outputFormat but sometimes that isn't enough.

e.g.

someMessage=Display this message with param {0}

in a resource bundle.

To display it on xhtml I normally do:

<h:outputFormat value="#{msg['someMessage']}"><f:param value="#{someBean.value}"/></h:outputFormat>

That works well when it's a simple case, but for more complex use cases it isn't enough. For example if I want the 'title' attribute of a commandLink to use the above resource bundle entry:

    <h:commandLink action="logout" title="#{msg['someMessage']}">
        <f:param value="#{someBean.value}" />
        <h:graphicImage library="images" name="image.png" />
    </h:commandLink>

which doesn't work. I also tried:

    <h:commandLink action="logout">
        <f:attribute name="title">
            <h:outputFormat value="#{msg['someMessage']}"><f:param value="#{someBean.value}"/></h:outputFormat>
        </f:attribute>
        <h:graphicImage library="images" name="image.png" />
    </h:commandLink>

which also doesn't work since f:attibute doesn't allow children.

Even if there is a hack to bypass this (e.g. using hover component from primefaces) there are other fields that might require a parameterized message.

Does anyone know of a way to use MessageFormat that takes an argument in a non-value field of a JSF component?

like image 651
Zak Avatar asked Aug 17 '12 04:08

Zak


1 Answers

You could create a custom EL function for this with which you can ultimately end up like:

<h:commandLink ... title="#{my:format(msg['someMessage'], someBean.value)}" />

You can use the MessageFormat API to perform the job, exactly as <h:outputFormat> is doing under the covers.

An alternative is to create a custom component which does the same as JSTL's good 'ol <fmt:message> which supports a var attribute to export the formatted message into the EL scope.

<my:outputFormat ... var="linkTitle">
    ...
</my:outputFormat>
<h:commandLink ... title="#{linkTitle}" />

Update: JSF utility library OmniFaces has #{of:formatX()} functions and a <o:outputFormat> component for the very purpose.

like image 119
BalusC Avatar answered Oct 21 '22 21:10

BalusC