I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?
Spring-side:
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("message", "hello");
return "index";
}
Client-side:
<script>
....
var m = ${message}; // not working
alert(m);
...
</script>
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript">
var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
</script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
var message =/*[[${message}]]*/ 'defaultanyvalue';
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[#{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
MAKE sure you have thymleaf on page already
//Use this in java
#Controller
#RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [( brackets which wrap the variable.
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the
URLs embedded in it. Here are the steps (if you are using Spring MVC)
#RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Assuming request attribute named "message":
request.setAttribute("message", "this is my message");
To read it in the html page using Thymeleaf template:
<script>
var message = "[[${message}]]";
alert(message);
</script>
Related
This is how we access [[${message}]] in JavaScript:
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
console.log(message);
/*]]>*/
</script>
Since I don't want to use inline JavaScript, I have referenced a JavaScript file as followed:
<script type="text/javascript" src="/js/app.js"></script>
How can I access [[${message}]] in a my external JavaScript file, app.js?
Thymeleaf 3 introduced new template modes, one of which is javascript. So in addition to your TemplateResolver that returns html, you need to configure a new TemplateResolver that returns javascript resources instead. Then you'd create a controller as normal except it would be serving your javascript:
#Controller
public class JavascriptController {
#RequestMapping("/js/app.js")
public String greeting(Model model) {
model.addAttribute("message", "Here is a message.");
return "/where/your/js/is/app.js";
}
}
It would use the model as normal to pass variables to your external javascript.
I'm adding an attribute to my ModelAndView in spring and after this i forwarding it to my thymeleaf view.
In the view i have the following code:
<script th:inline="javascript">
/*<![CDATA[*/
var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test";
var collectedValueJson = [[${collectedValues}]];
console.log(collectedUserJson);
/*]]>*/
</script>
Result from this is
var applicationName = 'collectedValues';
var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]';
That's fine. Now my wish for this is, that i can take the var application and access with this variable the modelattribute, but that's not working.
Result is this:
var tmp2 = ${applicationName};
An other try was, that i have access to the modelattribute with the syntax /*[[ ]]*/ from the first try:
var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/};
But result will be:
var tmp = ${'collectedValues'
i have no idea what can i try.
Any other suggestions?
Thank's in advance.
There is a workaround worth mentioning: Write out the attribute to
<span id="myvar" th:text="${attributeName}"></span>
and then read it in with JavaScript using
document.getElementById("myvar").value
or some similar jQuery call:
$('#myvar').text()
there is no way you can access model atributes hence they are on server side and they where lost when rendering jsp into HTML
You can:
<span id="span_id" style="display: none;" th:text="${attributeName}"></span>
and then in your Javascript:
document.getElementById("span_id").innerHTML
I'm using the current json structure of this:
jsonp = {"game":[
{"id":"1","gameImage":"qqq.jpg"}
],
"game":[
{"id":"2","gameImage":"hhh.jpg"}
]
}
I'm trying to just get back all the gameImage values. I tried the following but it just won't work. Any ideas?
<html>
<head></head>
<body>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="gameData.json"></script>
<script>
$(document).ready(function() {
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
alert(this['gameImage']);
});
});
</script>
</body>
</html>
Assuming the first code you show is in the file (incorrectly) named "gameData.json", what you're trying to parse isn't JSON (or JSONP), it's plain JavaScript.
So don't parse it.
Change
var obj = $.parseJSON(jsonp);
to
var obj = jsonp;
Notes :
JSON is a text based data interchange format. Your confusion might come from the many young developers using non-sensical expressions like "JSON object"...
You should avoid naming jsonp a variable holding a plain JavaScript object.
If you prefer to load a JSON file instead of executing a JavaScript file, then
remove the "jsonp = part to make it a real JSON file
remove the script element (as it's not JavaScript anymore)
load the JSON file using ajax
Here's how the JavaScript would be like :
$(document).ready(function() {
$.getJSON("gameData.json", function(obj){
$.each(obj, function() {
alert(this['gameImage']);
});
});
});
or, if you can afford not supporting IE8 :
$(document).ready(function() {
$.getJSON("gameData.json", function(arr){
arr.forEach(function(item){
console.log(item.gameImage); // yes, prefer the console over alert
});
});
});
I am responding to clicks on li's by using $.post to post to an action method in my MVC application.
I want to send a link back in Json.
Can I have this link render as html rather than text ? how ?
I tried this, just to test the html:
var link = "<b>Hi</b>";
var encoded = Server.HtmlEncode(link);
that came out as <b>Hi</b>
Surely there is just a Json.encode or visual studio method I can use and I don't have to format it myself? Have googled fairly extensively and can't find anything about an Json.encode
var link = "<b>Hi</b>";
var encoded = new JavaScriptSerializer().Serialize(link);
the page rendered "\u003cb\u003eHi\u003c/b\u003e"
If I send just the link variable, i.e:
var link = "<b>Hi</b>"
<b>Hi</b> renders
This is the line which sends it back:
return Json(new {Title = pTitle, Selection = pSelection, Link = pLink}, JsonRequestBehavior.AllowGet);
Starting to get frustrated, wtf!
Silly me, I didn't post enough code where the problem was:
<script type="text/javascript">
function TreeView_onSelect(e) {
...
$.post(url, id, function (data, textStatus) {
...
$("#panel-link").text(data.Link);
}
$("#panel-link").text(data.Link);
obv has to be
$("#panel-link").html(data.Link);
Try using JavaScriptSerializer:
var link = "<b>Hi</b>";
var encoded = new JavaScriptSerializer().Serialize(link);
Try to use javascript's decodeURI() function.
http://www.w3schools.com/jsref/jsref_decodeuri.asp
<script type="text/javascript">
var uri="mytest.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br />");
document.write(decodeURI(uri));
</script>
The output of the code above will be:
mytest.asp?name=st%C3%A5le&car=saab
mytest.asp?name=ståle&car=saab
I have the same problem with you and killing me whole day,
I solved this problem by using Json.NET
Sample code is :
Newtonsoft.Json.JsonConvert.SerializeObject(link);
Reference
http://json.codeplex.com/documentation
code :
<script type="text/javascript" src="http://127.0.0.1/Test.js#username=stackoverflow">
</script>
iwant to know ,how to get the username in Test.js
file
Test.js :
var username = ??
///////////// #username=stackoverflow
thanks advance
If you are trying to do all this on the client side, it's much better to use:
<script type="text/javascript">//<![CDATA[
var username = "stackoverflow";
//]]></script>
<script type="text/javascript" src="http://127.0.0.1/Test.js"></script>
That way, you don't need to tackle the issue of reading the src attribute of the script tag somehow.
The query portion of the URL is invalid. It should be:
http://127.0.0.1/Test.js?username=stackoverflow
The # is treated as a named anchor.
The gup function isn't good because the parameter is on the script tag, not the HTML output page.
The location object (location.href, location.search...) refers to the HTML page where the script included.
There are 2 other options:
Use this
Use #idealmachine answer. You can wrap the global variable with simple object in order to avoid conflict with other global JS variables