Gustavo
Gustavo

Reputation: 1418

How to use new line character inside EL string literal?

I need to print some text with multiple lines inside a text area using EL. When I do this:

<textarea rows="4">
    ${o.condition ? "blah" : "1. \n2. \n3. \n4."}
</textarea>

I get:

Unable to compile class for JSP

What is the equivalent to

<%=o.getCondition() ? "blah" : "1. \n2. \n3. \n4." %>

using EL?

Some suggest storing \n in a variable and using this variable within the expression.

Upvotes: 2

Views: 1367

Answers (2)

BalusC
BalusC

Reputation: 1108722

Depending on the EL implementation used, you may need to escape the backslash as well. As far as I'm concerned, this is true for Apache's EL implementation (as used in a.o. Tomcat, WebSphere, etc), but not for Oracle's EL implementation (as used in a.o. GlassFish, WildFly, etc). EL spec is itself not fully clear on this (yet).

<textarea rows="4">
    ${o.condition ? "blah" : "1. \\n2. \\n3. \\n4."}
</textarea>

But safer is to use the HTML entity notation instead. Linefeed is character U+000A which can in hexadecimal HTML entity notation be represented as &#xa;.

<textarea rows="4">
    ${o.condition ? "blah" : "1. &#xa;2. &#xa;3. &#xa;4."}
</textarea>

This way you're not dependent on the target runtime.

Upvotes: 0

RockAndRoll
RockAndRoll

Reputation: 2277

Assuming you can use jstl tags,You can achieve it like this.

<textarea rows="4">
<c:forTokens items="1.\n2.\n3.\n4." delims="\n" var="item">
     ${item} 
</c:forTokens>
</textarea>

Upvotes: 1

Related Questions