1

I want to use JSTL library in javascript.

My code is below.

<script type="text/javascript">
var grid_data = 
[
<c:forEach items="${LIST}" var="list" varStatus="status">               
<c:if test="${ status.index == 0 }">
{id:'${list.NOTICE_ID}'}
</c:if>
</c:forEach>
];
</script>

This code is working well, but it's not working with choose tag.
Is there any special reason? Can anybody help me?

// Syntax error on tokens ** especially in script not in html body **
<script type="text/javascript">
var grid_data = 
[ 
<c:forEach items="${LIST}" var="list" varStatus="status">               
<c:choose>
<c:when test="${ status.index == 0 }">
{id:'${list.NOTICE_ID}'}
</c:when>
<c:otherwise>
,    {id:'${list.NOTICE_ID}'}
</c:otherwise>
</c:choose>
</c:forEach>
]
</script>

enter image description here

user2940817
  • 61
  • 1
  • 4
  • Define "it's not working". What happens? Where is the ``. What is generated in both cases? – JB Nizet Oct 31 '13 at 09:53
  • Sorry there was editing errors. I add tag. "it's not working" means that there are an error. - "Syntax error on tokens. delete these tokens." – user2940817 Nov 01 '13 at 01:37

3 Answers3

2

Those are errors signalled by Eclipse, because Eclipse is unable to correctly validate JavaScript code syntax when it's intermingled with JSP code.

Deploy the JSP, run it, and see if it actually works when executed. It will probably run fine.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Cannot help you with the choose tag - this current code snippet cannot work (missing closing tag). What about adding comma after each but last element of the list as described in jstl foreach omit an element in last record ?

Community
  • 1
  • 1
Kojotak
  • 2,020
  • 2
  • 16
  • 29
0

the following approach may help to avoid ugly errors in eclipse:

  1. set a variable as it shown below:

    <c:set var="newVariable">
    {
    <c:forEach var="entry" items="${variableFromServerAsMap}" varStatus="status">
        "<c:out value='${entry.key}'/>" : "<c:out value='${entry.value}'/>}"<c:if test="${not status.last}">,</c:if>
    </c:forEach>
    };
    

  2. and use the newVariable variable in the javascript sections as the following:

    <script type="text/javascript">
        var my_js_data = <c:out value="${newVariable}" escapeXml="false"/>
    </script>
    

The output should be similar to the following:

<script type="text/javascript">
    var my_js_data = {

            "some_param_key" : "some_param_value",
            "some_param_key_2" : "some_param_value_2",

    };
</script>
Cyril Deba
  • 1,200
  • 2
  • 16
  • 30