jstl inside javascript

Is it possible to use jstl inside javascript?

I'm tying to set <c:set var="abc" value="yes"/>

and then later access this value in html and execute some code. My problem is the c:set is executing always even if the javascript condition is false.

<script type="text/javascript">
var v1 = false;
<c:set var"abc" value="yes"/>

if(v1){
  <c:set var"abc" value="no"/>
}
</script>

In the above code, even if v1 is false 'no' is setting to abc.

Answers:

Answer

There is no meaning to the idea of being "inside Javascript" when you're talking about server-side JSP interpretation. There's just no such thing as Javascript as far as that domain is concerned.

Thus, yes, it's possible, if you mean that you want to do something like

var something = '${abc}';

Note that you have to be careful with quoting and special characters. The JSTL fn:escapeXml() function is useless when you're interpolating a JSP variable into a part of the page that will be interpreted as Javascript source by the browser. You can either use a JSON library to encode your strings, or you can write your own EL function to do it.

Answer

This is a quite old thread, but it is one I bumped into when I had the same problem. Since I thought of a solution myself, I will post it here in case it helps somebody in the future.

The html ( or jsp ) file looks for the text inside the external file declared as javascript source.

Tomcat ( or similar ) only interpret JSTL tags within files with the .jsp extension ( or maybe some other ones too, but it is irrelevant for this answer ).

So, rename your .js file to give it a .jsp extension ( javascript.js to javascript_js.jsp for example )

Add those lines at the top of javascript_js.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

and just leave the code it unchanged.

Obviously, you also need to add more prefixes if you use some other than c: in the header.

If you use Eclipse ( don't know about other IDEs ), it will assume it is not a javascript file and you lose the colour scheme for the different keywords ( var, function and so on ), var name auto completion and auto indentation.

To fool the IDE, you can add

// <script> 

as a js comment, before the actual code ( after the "<%@" declarations ), and

// </script>

at the end of the file, again as a js comment.

It worked for me.

Answer
<script>
    <c:set var="myVal" value="Hello"/> 

    var val1="${myVal}";

</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.