I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.
Here is a solution I found. It doesn't seem very elegant, though:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>
${fn:replace(item.comments, newLineChar, "; ")}
Just use fn:replace() function to replace \n by ;.
${fn:replace(data, '\n', ';')}
In case you're using Apache's EL implementation instead of Oracle's EL reference implementation (i.e. when you're using Tomcat, TomEE, JBoss, etc instead of GlassFish, Payara, WildFly, WebSphere, etc), then you need to re-escape the backslash.
${fn:replace(data, '\\n', ';')}
This is similar to the accepted answer (because it is using Java to represent the newline rather than EL) but here the <c:set/> element is used to set the attribute:
<c:set var="newline" value="<%= \"\n\" %>" />
${fn:replace(myAddress, newline, "<br />")}
The following snippet also works, but the second line of the <c:set/> element cannot be indented (and may look uglier):
<c:set var="newline" value="
" /><!--this line can't be indented -->
${fn:replace(myAddress, newline, "<br />")}
This solution is more elegant than your own solution which is setting the pagecontext attribute directly. You should use the <c:set> tag for this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="newLine" value="\n"/>
${fn:replace(data, newLine, "; ")}
BTW: ${fn:replace(data, "\n", ";")} does NOT work.
This does not work for me:
<c:set var="newline" value="\n"/>
${fn:replace(data, newLine, "; ")}
This does:
<% pageContext.setAttribute("newLineChar", "\n"); %>
${fn:replace(item.comments, newLineChar, "; ")}
You could create your own JSP function.
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html
This is roughly what you need to do.
Create a tag library descriptor file
/src/META-INF/sf.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>sf</short-name>
<uri>http://www.stackoverflow.com</uri>
<function>
<name>clean</name>
<function-class>com.stackoverflow.web.tag.function.TagUtils</function-class>
<function-signature>
java.lang.String clean(java.lang.String)
</function-signature>
</function>
</taglib>
Create a Java class for the functions logic.
com.stackoverflow.web.tag.function.TagUtils
package com.stackoverflow.web.tag.function;
import javax.servlet.jsp.tagext.TagSupport;
public class TagUtils extends TagSupport {
public static String clean(String comment) {
return comment.replaceAll("\n", "; ");
}
}
In your JSP you can access your function in the following way.
<%# taglib prefix="sf" uri="http://www.stackoverflow.com"%>
${sf:clean(item.comments)}
If what you really need is a \n symbol you can use the advice from here:
${fn:replace(text, "
", "<br/>")}
or
<c:set var="nl" value="
" /><%-- this is a new line --%>
This includes the new line in your string literal.
You should be able to do it with fn:replace.
You will need to import the tag library into your JSP with the following declaration:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Then you can use the following expression to replace occurrences of newline in ${data} with a semicolon:
${fn:replace(data, "\n", ";")}
The documentation is not great on this stuff and I have not had the opportunity to test it.
\n does not represent the newline character in an EL expression.
The solution which sets a pageContext attribute to the newline character and then uses it with JSTL's fn:replace function does work.
However, I prefer to use the Jakarta String Tab Library to solve this problem:
<%# taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1" %>
...
<str:replace var="result" replace="~n" with=";" newlineToken="~n">
Text containing newlines
</str:replace>
...
You can use whatever you want for the newlineToken; "~n" is unlikely to show up in the text I'm doing the replacement on, so it was a reasonable choice for me.
This is a valid solution for the JSP EL:
"${fn:split(string1, Character.valueOf(10))}"
More easily:
<str:replace var="your_Var_replaced" replace="\n" with="Your ney caracter" newlineToken="\n">${your_Var_to_replaced}</str:replace>
You could write your own JSP function to do the replacement.
This means you'd end up with something like:
<%# taglib prefix="ns" uri="..." %>
...
${ns:replace(data)}
Where ns is a namespace prefix you define and replace is your JSP function.
These functions are pretty easy to implement (they're just a static method) although I can't seem to find a good reference for writing these at the moment.
In the value while setting the var, press ENTER between the double quotes.
${fn:replace(data, newLineChar, ";")}
For the record, I came across this post while tackling this problem:
A multi-line string in JSTL gets added as the title attribute of a textarea. Javascript then adds this as the default text of the textarea. In order to clear this text on focus the value needs to equal the title... but fails as many text-editors put \r\n instead of \n. So the follownig will get rid of the unwanted \r:
<% pageContext.setAttribute("newLineChar", "\r"); %>
<c:set var="textAreaDefault" value="${fn:replace(textAreaDefault, newLineChar, '')}" />
Related
I have this code in my gsp file:
<span class="highlighted-data-value">${address}</span>
address variable holds a value similar to:
Address line 1, City, Country
I want to line break on comas, but it looks like I am not able to do so.
Is there a way to do replaceAll inside that gsp file? Something like ${address.replaceAll(",","\\n")}
Ideally I would not want to use the controller, but to do it directly in gsp file.
${address.replaceAll(",","\\n")} didn't produce expected result, because it broke String into 3 lines, but HTML renders it as a single line when there is no <br /> tag. Instead you can try breaking your String as:
${raw(address.replaceAll(',', '<br />'))}
This will produce a result that should render an address broken to 3 lines:
<span class="highlighted-data-value">Address line 1<br /> City<br /> Country</span>
Alternatively you can split this String in controller, pass a list to a view and then use <g:each in=""></g:each> loop.
I'm trying to trim ending white space from AlertTitle in an ascx transforamtion. I know there is TrimEnd, but i'm drawing a blank getting it to work.
The V9 Documentation has a method for this(https://docs.kentico.com/display/K9/Adding+custom+methods+to+transformations) but i don't want to fix the length.
Here's the transformatin code snippet.
<asp:placeholder id="alert" runat="server" Visible="false">
<li data-date="<%# Eval("AlertDate") %>">
<p class="alert-date"><%# FormatDateTime(Eval("AlertDate"), "MMMM dd, yyyy") %> </p>
<p class="alert-copy"><%# Eval("AlertTitle") %> <%# IfEmpty(Eval("AlertCopy"),"", "... <a href='" + GetDocumentUrl() + "'>" + CMS.Helpers.ResHelper.GetString("kff.Generic-ReadMore") + "</a> »") %></p>
</li>
</asp:placeholder>
In addition to using Trim() or TrimEnd() in the transformation, you can also set it up so Kentico will automatically trim the fields when the form is submitted by checking the "Trim" checkbox under "advanced" Editing control settings.
Like so:
You probably need to cast the ouput of Eval to a string first:
<%# ((string)Eval("AlertTitle")).TrimEnd() %>
In v8 and newer, you can also use a different version of Felix's answer
<%# Eval<string>("AlertTitle").TrimEnd() %>
I have ran into a particularly strange problem when implementing a RichFaces tool tip component. In my project I have a table that displays a list of Strings that are entered by the user, and I want there to be a pop-up of additional information when a user mouses over the strings in the list.
One of the requirements is that any string that is more than one word must contain double quotes "" when input by the user--e.g. a single word would be input as Java vs. a phrase "Java is cool".
So, I added a <rich:toolTip> to render additional info if it exists--and it works, except for strings that contain double-quotes. For example (as it's displayed in the table) "sample string" will not show additional information on mouseover.
My JSF code is simply:
<h:outputText id="keywordText" value="#{keywordData.keyword}"/>
<rich:toolTip for="keywordText" rendered="#{keywordData.comments != null}" value="#{keywordData.comments}"/>
Like I said, this works for words/strings that do not contain quotes. I am wondering if there is a workaround within JSF/RichFaces I can use in order to get this to work properly with a string that contains quotes. Or perhaps some assistance in writing a custom JavaScript function that forces or "tricks" RichFaces into handling quotation marks in a string correctly?
Thanks for any help in advance!
Edit: I am using RichFaces 3.3.3
In the page source, for the string "Testing Quotes" (does not work) I found this:
<span id="j_id138:j_id144:keywordTable:"Testing Quotes":keywordText">"Testing Quotes"</span>
<span id="j_id138:j_id144:keywordTable:"Testing Quotes":j_id159" class="rich-tool-tip " style="z-index:99; ">
<span id="j_id138:j_id144:keywordTable:"Testing Quotes":j_id159content">
<p>This comment should display</p>
</span>
<span id="j_id138:j_id144:keywordTable:"Testing Quotes":j_id159script" style="display:none">
<script id="scriptj_id138:j_id144:keywordTable:" quotes":j_id159"="" testing="" type="text/javascript">
new ToolTip("j_id138:j_id144:keywordTable:"Testing Quotes":j_id159","j_id138:j_id144:keywordTable:"Testing Quotes":keywordText",{'showEvent':'mouseover'} );
</script>
</span>
You can see that the quotations in the string itself (which appears to supposed to be part of the id attribute) are being misinterpreted in the new ToolTip parameters. And for a string testkeywordawesome without quotes you can see it works (because it does not contain quotes):
<span id="j_id138:j_id144:keywordTable:testkeywordawesome:keywordText">testkeywordawesome</span>
<span id="j_id138:j_id144:keywordTable:testkeywordawesome:j_id159" class="rich-tool-tip " style="z-index: 99; visibility: hidden; display: none; left: 63.7833px; top: 210.75px;">
<span id="j_id138:j_id144:keywordTable:testkeywordawesome:j_id159content">
<p>the best comment in the world</p>
</span>
<span id="j_id138:j_id144:keywordTable:testkeywordawesome:j_id159script" style="display:none">
<script id="scriptj_id138:j_id144:keywordTable:testkeywordawesome:j_id159" type="text/javascript">
new ToolTip("j_id138:j_id144:keywordTable:testkeywordawesome:j_id159","j_id138:j_id144:keywordTable:testkeywordawesome:keywordText",{'showEvent':'mouseover'} );
</script>
</span>
Edit2: The tool tips exists in a rich:column, of which exists in a rich:extendedDataTable. Below are their code:
<rich:extendedDataTable value="#{keywordEntry.globalKeywordsDataModel}"
rendered="#{fn:length(keywordEntry.globalKeywords) gt 0}"
styleClass="removeEDTSortIcon removeEDTContextMenu"
id="keywordTable" rowClasses="row1, row2"
var="keywordData" rows="0" noDataLabel=" "
headerClass="#{displayHeader == null or displayHeader ? 'rich-table-header' : 'hide'}"
rowKeyVar="keywordRowIdx" enableContextMenu="false"
sortMode="#{globalKeywordListSort.multiSortEnabled ? 'multi' : 'single'}"
sortPriority="#{globalKeywordListSort.sortOrderList}"
width="#{eStaffUser.userKeywordAdmin ? '750px' : '750px'}"
height="#{((fn:length(keywordEntry.globalKeywords)*30 + 50) lt 480) ? (fn:length(keywordEntry.globalKeywords)*30 + 50) : 480}px"
>
and
<rich:column id="#{globalKeywordSortFieldEnumBean.KEYWORD}" selfSorted="false" width="#{eStaffUser.userKeywordAdmin ? '48%' : '52%'}" sortBy="#{keywordData.keyword}"
sortOrder="#{globalKeywordListSort.dataTableColumnSortClass[globalKeywordSortFieldEnumBean.KEYWORD].sortOrder}">
id="j_id138:j_id144:keywordTable:"Testing Quotes":keywordText"
This means that one of the parents of <h:outputText id="keywordText"> has its id defined by something that evaluates to "Testing Quotes", that's obviously bad.
OK, so the root of the issue was that the rich:extendedDataTable uses an ID supplied by each entry to generate a unique ID for each table row. So the problem ended up being in the underlying "Model Managed-Bean" that implemented a generic data entity interface, this interface defines a getEntityId() method and in this case, the "ID" returned was the keyword value itself, since there was no true (i.e., database) entity ID such as a primary key:
public class KeywordDataBean implements SummaryDataEntityIF<String>
The problem was resolved by changing the interface's implementation to Integer and returning the hash as the unique ID for each keyword object:
public class KeywordDataBean implements SummaryDataEntityIF<Integer>
This forced the html id generated by the rich:extendedDataTable to be a simple integer number instead of a (keyword) string containing quotes, allowing the rich:toolTip to work properly.
Hi i have this method in managed bean.
public String instructionsText() {
String text = "Whether your web site needs a simple 'face lift' <br /> "+
" major 'reconstructive surgery,' the staff of"
return text;
}
in my jsf page :
<img src="http://icons.iconarchive.com/icons/aroche/delta/32/Help-icon.png" style="float:right" onclick="PF('dlgi').show();" alt="help" />
I want a line break in string text at the place of <br />.But i tried in different ways
(\n, \r\n, \r ,<br> , <br />).Nothing worked.Help would be greatly appreciated.Thank you.
There is a escape attribute for h:outputText, a Boolean flag which indicates whether to escape the HTML content or not.
By default the value is true. Set the value as escape="false".
You can find the Doc Ref HERE.
I have a model called MSG and it has a content:string in it.
In the MSG form I have a
<%= f.text_area :content %>
for the user to input the message.
However, when I display :content using <%= Msg.content %> the text has no "enter"/CR or spaces, tabs etcs and it is just a long line of text.
How do I force displaying the CR that that user put?
example:
content:
Hello,
buy milk.
instead I get
Hello, buy milk.
thanks
You can use simple_format to properly display line breaks:
<%= simple_format(Msg.content) %>