Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a String in EL?

How do I get the promoPrice variable to print as part of the string ONLY $4.67?

<c:set var="promoPrice" value="4.67" />
<p>${(promoPrice != null) ? "ONLY $${promoPrice}" : "FREE"}</p>
like image 965
alquatoun Avatar asked Jun 09 '11 18:06

alquatoun


2 Answers

If you're already on EL 3.0 (Java EE 7; WildFly, Tomcat 8, GlassFish 4, etc), then you could use the new += operator for this:

<p>${not empty promoPrice ? 'ONLY $' += promoPrice : 'FREE'}</p> 

If you're however not on EL 3.0 yet, then use EL 2.2 (Java EE 7; JBoss AS 6/7, Tomcat 7, GlassFish 3, etc) capability of invoking direct methods with arguments, which you then apply on String#concat():

<p>${not empty promoPrice ? 'ONLY $'.concat(promoPrice) : 'FREE'}</p> 

Or if you're even not on EL 2.2 yet, then use JSTL <c:set> to create a new EL variable with the concatenated values just inlined in value:

<c:set var="promoPriceString" value="ONLY $${promoPrice}" /> <p>${not empty promoPrice ? promoPriceString : 'FREE'}</p> 

In your particular case, another way is to split the expression in two parts:

<p>${not empty promoPrice ? 'ONLY $' : 'FREE'}${promoPrice}</p> 

If ${promoPrice} is null or empty, it won't be printed anyway.

like image 114
BalusC Avatar answered Oct 23 '22 20:10

BalusC


Straight jstl way

<c:set var="promoPrice" value="4.67" />
<p>
<c:choose>
    <c:when test="${(promoPrice != null)}">
        ONLY $${promoPrice}
    </c:when>
    <c:otherwise>
        FREE
    <c:otherwise>
</c:choose>
</p>
like image 39
joekarl Avatar answered Oct 23 '22 19:10

joekarl