如何在 EL 中连接字符串? [英] How to concatenate a String in EL?
问题描述
如何将 promoPrice
变量打印为字符串 ONLY $4.67
的一部分?
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>
推荐答案
如果您已经在使用 EL 3.0(Java EE 7;WildFly、Tomcat 8、GlassFish 4 等),那么您可以使用新的 +=
运算符:
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>
如果您还没有使用 EL 3.0,则使用 EL 2.2(Java EE 7;JBoss AS 6/7、Tomcat 7、GlassFish 3 等)调用带参数的直接方法的功能,然后您将其应用于String#concat()
:
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>
或者,如果您甚至还没有使用 EL 2.2,那么使用 JSTL
来创建一个新的 EL 变量,其中的连接值只是内联在 value 中:
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>
如果 ${promoPrice}
为 null 或为空,则无论如何都不会打印.
If ${promoPrice}
is null or empty, it won't be printed anyway.
这篇关于如何在 EL 中连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!