开发者

Super Simple JSP Javascript Question

开发者 https://www.devze.com 2023-03-22 22:23 出处:网络
I am truncating a string if it is beyond a certain length. I\'m super new to jsp, so I\'m doing it the only way I know how. I have a bit of javascript that will create a new var with the truncated str

I am truncating a string if it is beyond a certain length. I'm super new to jsp, so I'm doing it the only way I know how. I have a bit of javascript that will create a new var with the truncated string. I need to use this new displayTag string within the html. However, I realized I can't use that var outside of the script tags. How can I achieve this?

 <script type="text/ja开发者_JAVA技巧vascript">
    var displayTag = "${example.name}";
    if(displayTag.length > 15) {displayTag=displayTag.substring(0,15)+"..."};
    alert(displayTag); // for testing
 </script>

 <a href="some_link"><c:out value=displayTag/></a> // I know this line will not actually work


fn:substring and fn:length are probably what you're after.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:choose>
   <c:when test="${fn:length(example.name) > 15}">
      ${fn:substring(example.name, 0, 15)}...
   </c:when>
   <c:otherwise>
      ${example.name}
   </c:otherwise>
</c:choose>


Your ${example.name} is an EL expression using a JSP variable; displayTag is a Javascript variable, so as you say <c:out value=displayTag/> won't work because <c:out ...> runs on the server before the page is ever sent to the browser, so the javascript variable doesn't even exist.

I prefer to do this kind of thing on the server so it works even if Javascript is off or fails on an error.

An EL expression to do this could be

${fn:length(example.name) <= 15 ? example.name : fn:substring(example.name, 0, 15) + '...'}

(I haven't test that) The + operator doesn't work for string concatenation in EL, and there are no fn:concat or fn:append functions in standard JSTL, although concat does seem to be part of <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>

In that case it would be

${fn:length(example.name) <= 15 ? example.name : x:concat(fn:substring(example.name, 0, 15), '...')}

That is, if the length of example.name is 15 or less just use it, otherwise take the substring and append "...", all done on the server as part of the JSP processing.

0

精彩评论

暂无评论...
验证码 换一张
取 消