Convert String inside h:outputText into capitalize String?

user1555524 picture user1555524 · Nov 17, 2012 · Viewed 21k times · Source

How can I convert a String in h:outputText? Here is the code of h:outputText:

<h:outputText value="#{item.label} : " />

I tried using this,

<s:convertStringUtils format="capitalize" trim="true"/>

But it gives me error : "no tag was defined for name: convertStringUtils"

Answer

BalusC picture BalusC · Nov 17, 2012

There are several ways.

  1. Use CSS text-transform: capitalize property.

    <h:outputText value="#{bean.text}" styleClass="capitalized" />
    

    with

    .capitalized {
        text-transform: capitalize;
    }
    
  2. Create a custom Converter.

    <h:outputText value="#{bean.text}" converter="capitalizeConverter" />
    

    with

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null || ((String) modelValue).isEmpty()) {
            return null;
        }
    
        String string = (String) modelValue;
        return new StringBuilder()
            .append(Character.toTitleCase(string.charAt(0)))
            .append(string.substring(1))
            .toString();
    }
    
  3. Use OmniFaces' of:capitalize() function.

    <html ... xmlns:of="http://omnifaces.org/ui">
    ...
    <h:outputText value="#{of:capitalize(bean.text)}" />
    

The <s:convertStringUtils> which you're trying is not from Seam. It's from MyFaces Sandbox.