How do I include a JavaScript variable inside thymeleaf for checking a condition?
Tried:
<div th:if="${myVariable == 5}">
//some code
</div>
but it's not working.
What you are trying to do won't work, since Thymeleaf processes the template on the server side and therefore the variables it has access to are the ones defined in it's model.
If you had myVariable in the model on which Thymeleaf is operating, it would work.
If what you want is to set the value of a Javascript variable in a Thymeleaf template, you can do the following:
<script th:inline="javascript">
/*<![CDATA[*/
...
var myVariable= /*[[${myVariable}]]*/ 'value';
...
/*]]>*/
</script>
Inside the script you could have any logic you want including hide/show etc.
Check out this part of the documentation for mode details.
With thymeleaf 3, the CDATA block had to be removed to reference my variable inline or the parser ignored it completely. This syntax worked successfully for me post upgrade:
<script th:inline="javascript">
var myVariable = [[${#vars.myVar}]];
...
</script>
Note: if you also referenced your variables as [[${#ctx.variables.myVar}]], it will no longer work in thymeleaf 3 as ctx no longer has a variable named variables.
I think I understand your question and I don't think it's possible. Thymeleaf does server side rendering and thus it won't use javascript variables since those won't be created on the server.
What you can try is write an initializer function that will hide/show certain DOM elements. You can approach this multiple ways for instance give ids to them and change their class list to add "display:none" style.
<script>
// <![CDATA[
...Your script, here
// ]]>
</script>
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
I have jsp file in which i am getting a List of objects from my java action class (struts2) and displaying it.Now i want to access these list objects inside my javascript method.How to do this?
mycode.jsp
<script type="text/javascript">
//Some functions
jQuery(document).ready(function(){
$("#dialog-form").trigger('click');
//Problem is how to access myObjectsList here
//and which is of type MyCustom class with 2 class variables(i.e., name and id)
//I need to access name and id as well
var colFamilies ='${myObjectsList}';
alert(myObjectsList);
});
//Some functions
</script>
<html>
<!-- my code -->
<s:iterator value="myObjectsList" var="myObject">
<li><h4>
<s:property value="#myObject.name" />
</a>
</h4></li>
<!-- my code -->
</html>
Please give me some suggestions
I am tired of goggling since 2 days
I believe the problem is that you are attempting to assign a list of some non-primitive type as a JavaScript array.
This answer may be helpful to you. In short, you may need to do some converting rather than directly assigning this object. Since the linked answer uses a static utility method, you may need to consider doing the conversion on your backend.
Is this possible? I want to be able to pass java bean data into javascript objects, but I'd really prefer not to muck up my jsp pages with a bunch of inline script tags. I like to keep my javascript separate in external files, but how do you accomplish something like this without using inline js?
<script type="text/javascript">
var variableFromServer = '${someBean.someProperty}';
</script>
You can create a JSON file with all the data and either include it inline or fetch the JSON through Ajax - that way you don't clutter the markup with data. See http://json-taglib.sourceforge.net/ for an example of a JSP-JSON template.
I'm not sure if this is worth it but one alternative will be to set the desired value in an input filed with type="hidden" and get it's in js. But this will also pass this parameter in GET and POST request from the form.
You can either do what you're doing in the snippet (do you consider that "inline JS"?), create a div of JSON with data in it (exposed as a single string) and process it, pass JS files through the JSP process (or use a different templating system for dynamic JS pages), etc.
I'm not a huge fan of processing JS files through JSP; I'll often create an object containing all the info my JS needs in a <script> tag at the bottom of the body before including my real JS. It's kind of lazy, but it's straight-forward.
One option that I've used in the past is to configure the servlet container to run the JSP interpreter on *.js files. How to set this up will depend upon what server you are running.
Note that if you want to access any request attributes this way you will need to set them up as part of the request that fetches the JavaScript file(s) (i.e. you will have to have a servlet in front of your JavaScript...or as an alternative you can use an include directive to bring in the scripts instead of a <script src='...'> tag). Session attributes you can access without needing to have a custom servlet in front of your JavaScript files.
I'm a fan of doing it the simple and easy way, so I'd create a single script element that has a minimal number of JS variables set from Java - ideally a single JS variable that is set to an object with different properties for all the different bits of data you need to pass through. Your Java code basically just outputs JSON that will be interpreted as an object literal in the JS. Immediately after that include any external scripts - because they're included afterwards they can use the variables already created.
You can put the above in the head or at the end of the body. (Or in the middle, but that doesn't really make sense.)
<html>
<head>
</head>
<body>
<!-- actual HTML markup here -->
<script>
var variableFromServer = '${someBean.someProperty}',
objectFromServer = /* jsp to spit out JSON here as appropriate */ ;
</script>
<!-- external files included after the above will be able to access
those variables -->
<script src="external1.js" type="text/javascript"></script>
<script src="external2.js" type="text/javascript"></script>
<script src="etc.js" type="text/javascript"></script>
</body>
</html>
You certainly don't need "a bunch of inline script tags" - even if it doesn't make sense to put all the values in a single object at least create all the variables in a single script element, and then all of your other JS can be in an external file.
(Add namespacing as required.)
arrays.jsp:
//...
var x = <c:out value="${x}"/>
<c:if test="${empty doExternal}">
processExternalArrays();
</c:if>
//...
I want to minify/obfuscate JavaScript contained in a large JSP file in which numerous JSP/JSTL variables are mixed into the JavaScript code such as in the snippet above.
The code relies on variables populated using server-side logic and then passed to the client-side code, as above.
I'm already minifying my JS files using YUI compressor but I don't know what to do about the JavaScript code in my JSPs.
Is it possible to minify/obfuscate this code, given that it is dynamically created?
Probably the best solution for you would be use Granule JSP tag.
You can download it at
http://code.google.com/p/granule/
code sample is:
<g:compress>
<script type="text/javascript" src="common.js"/>
<script type="text/javascript" src="closure/goog/base.js"/>
<script>
goog.require('goog.dom');
goog.require('goog.date');
goog.require('goog.ui.DatePicker');
</script>
<script type="text/javascript">
var dp = new goog.ui.DatePicker();
dp.render(document.getElementById('datepicker'));
</script>
</g:compress>
...
Have you taken a look at htmlcompressor? In short it's a:
Java HTML/XML Compressor is a very
small, fast and easy to use library
that minifies given HTML or XML source
by removing extra whitespaces,
comments and other unneeded characters
without breaking the content
structure.
It's main function is so compress HTML and XML, but it also comes with JSP tags that can be used to compress inline JavaScript blocks by leveraging YUI Compressor. Check out the Google Code page, especially the Compressing selective content in JSP pages section.
I don't see other ways than fully delegating the job to pure JS with help of Ajaxical powers in combination with a Servlet which returns the desired information on an Ajax request (in flavor of JSON?).
E.g. in Servlet
Map<String, Object> data = new HashMap<String, Object>();
data.put("doExternal", doExternal);
data.put("x", x);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data)); // Gson is a Java-JSON converter.
and in JS (with little help of jQuery since it makes the Ajax works less verbose)
$.getJSON('servleturl', function(data) {
var x = data.x;
if (!data.doExternal) {
processExternalArrays();
}
});
This way you end up with clean JS without server-side specific clutter.
Ensure that your output is gzip encoded (apache mod_deflate). Minimizing the html/js first may make it a bit smaller, but not by much.
If you can't, or don't want to, move your JavaScript out of your HTML, one possibility would be to create a tag handler that wraps the content of your <script> tags:
<script type="text/javascript"><js:compress>
...
</js:compress></script>
The handler could probably extend SimpleTagSupport. You'd then have to investigate the Java APIs for compressors/minifiers, like YUI Compressor or dojo ShrinkSafe, and use them to process the tag body.
Edit: Sorry, I skimmed the other answers and it appears that Zack Mulgrew might be referencing a taglib that already does exactly what I'm suggesting...
Edit2: Yup, JavaScriptCompressorTag. Guess I'll have to up-vote his answer ;-)...
I have the following simple script, which I am using to dynamically create the list elements in a <ul>
<script type="text/javascript">
function generate(){
var arr = new Array();
<c:forEach items="${articles}" var="a" varStatus="status">
$('#listitems').append(
"<li>"+${a.title}+"</li>"
);
arr[${status.index}] ="${a.slideShow.images}";
</c:forEach>
}
</script>
My problem stems from the images attribute. Every article has a slideshow and every slideshow has a list of images. I want to pull out the very first image from the list of images via the jave list.get(index); I want to do something like "${a.slideShow.images.get(0)}";. The get() is a java method from the list object.
Any ideas?
In EL you can use the brace notation to access a List element by index. Thus, the following should do:
arr[${status.index}] = "${a.slideShow.images[0]}";
This will behind the scenes do exactly as you proposed: a.getSlideShow().getImages().get(0).
That said, you normally declare JS arrays like follows:
var arr = [];
The new keyword is considered discouraged in JS.
As those who commented on your question suggest, this is a common misunderstanding. By the time your JavaScript executes (in the browser), Java and JSP and JSTL are no longer available. The JSTL/JSP execute at the server to create source/HTML that is then sent to the client.
View source on your page - it might shed some light. You should not see the JSP/JSTL you include above.