Extend h: outputText for custom functions

I have been using JSF + RF for more than 2 years and have not had the opportunity to expand the existing capabilities of the components.

Now I have to crop the string and display it if its more than 25 characters.

This has been achieved as shown below.

                        <c:choose>
                            <c:when test="#{fn:length(teststep.name) > 25}">
                                <h:outputText title="#{teststep.name}" value="#{fn:substring(teststep.name, 0, 25)}..."/>
                            </c:when>
                            <c:otherwise>
                                <h:outputText title="#{teststep.name}" value="#{teststep.name}"/>
                            </c:otherwise>
                        </c:choose>

But I use this code in many places (and I want the template code of 8 lines not to be executed every time), so I thought about custom h: outputText to provide the functionality of the finish.

Could you let me know how to write a custom tag in JSF

Regards, Satya

+5
source share
1 answer

Assuming you are using JSP not Facelets, put the contents in a file .tagin /WEB-INF, for example /WEB-INF/tags/outputLimitedText.tag.

<%@ tag body-content="empty" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<c:choose>
    <c:when test="#{fn:length(value) > maxlength}">
        <h:outputText title="#{value}" value="#{fn:substring(value, 0, maxlength)}..."/>
    </c:when>
    <c:otherwise>
        <h:outputText title="#{value}" value="#{value}"/>
    </c:otherwise>
</c:choose>

:

<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %> 
...
<my:outputLimitedText value="#{teststep.name}" maxlength="25" />

Converter.

<h:outputText title="#{teststep.name}" value="#{teststep.name}">
    <f:converter converterId="substringConverter" />
    <f:attribute name="maxlength" value="25" />
</h:outputText>

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    String string = (String) value;
    int maxlength = Integer.valueOf((String) component.getAttributes().get("maxlength"));

    if (string.length() > maxlength) {
        return string.substring(0, maxlength) + "...";
    } else {
        return string;
    }
}

EL.

<h:outputText title="#{teststep.name}" value="#{util:ellipsis(teststep.name, 25)}">

EL: EL?

+10

All Articles