Thymeleaf: access map with variable key - javascript

This is my model.
Map <String, String>
e.g.
{ sam: "NY", tom: "SF", sue: "WN" }
How can I access the value from JavaScript if I have the key in a variable?
// mod is the model
var key = "sam";
var foo = [[${mod.get ("sam")}]]; // key by string -> foo is defined (OK)
var bar = [[${mod.get (key)}]]; // key by variable -> bar is undefined

You can pass the full Java map to your JavaScript code in your Thymeleaf template:
<script th:inline="javascript">
var key = "sam";
var mymap = [[${mod}]];
var bar = mymap[key];
console.log( bar );
</script>
Thymeleaf will create the following JavaScript (as seen in your rendered web page):
var key = "sam";
var mymap = {"sue":"WN","tom":"SF","sam":"NY"};
var bar = mymap[key];
console.log( bar ); // this prints "NY" to the browser console
The key point here is: Thymeleaf only exists on the server - it cannot execute JavaScript commands (on the server) - and there is no variable called key in your model that you pass to Thymeleaf.
Therefore the key in the Thymeleaf expression ${mod.get (key)} is null.
Another way around this is to add "sam" to the model in your Java code - for example:
model.put("key", "sam");
Or, for Spring:
model.addAttribute("key", "sam");
Now, there is a valid value for key, which can be used to evaluate the Thymeleaf expression ${mod.get (key)} on the server.
But this does not use the JavaScript line var key = "sam";.
This option may not be possible - it depends on where the value "sam" originates. If it's not available to your Java code, this is obviously not going to help you.
Reference: See Advanced inlined evaluation and JavaScript serialization for more details.

Related

How can i mix razor syntax and javascript syntax to change a hashtable value using a javascript var as key

I have a model in my application that has a hashtable. In my index.cshtml i want to set the value of a particular entry using javascript. Below is my piece of code:
$('input.optionselect').change(function () {
var id = $(this).attr('id');
alert(#this.Model.checkHT[
#:id;
] = false);
});
i get the error:
Cannot convert lambda expression to type 'object' because it is not a delegate type
You can get the hashtable as javascript object with this snippet:
<script type="text/javascript">
var hashtable = #Html.Raw(Json.Encode(Model.YourHashtable)
</script>
After that you will be able to access your data by value:
hashtable["sample"]

Using variable names where single quotes are expected

This is the Google RankTracker found here
<script>
if (document.referrer.match(/google\.com/gi) && document.referrer.match(/cd/gi)) {
var myString = document.referrer;
var r = myString.match(/cd=(.*?)&/);
var rank = parseInt(r[1]);
var kw = myString.match(/q=(.*?)&/);
if (kw[1].length > 0) {
var keyWord = decodeURI(kw[1]);
} else {
keyWord = "(not provided)";
}
var p = document.location.pathname;
ga('send', 'event', 'RankTracker', keyWord, p, rank, {'nonInteraction': 1});
dataLayer.push({'eventCategory':'RankTracker','eventAction':keyWord,'eventLabel':p,'eventValue':rank 'event':'RankTracker'});
}
</script>
I'm trying to get this working with Google Tag Manager, (the dataLayer.push({... section at the bottom), but I'm not sure the variables are working (although they work with the Universal Analytics ga('send'...) portion
Should calling the variables as I have done work in this case?
My main concern is the lack of single quotes around the values
BTW, if anyone is wondering I have set up macros in GTM for eventCategory, etc., and my rule for firing is that event is equal to RankTracker
Should calling the variables as I have done work in this case?
My main concern is the lack of single quotes around the values
Assuming you mean the keyword, p, and rank values used on the right-hand side of the : in a property initializer, those are used correctly and do not need quotes.
Here's a simpler example:
var foo = "testing";
var obj = {prop: foo};
console.log(obj.prop); // "testing"
I don't know much about Google RankTracker, but I do know you need a comma between those these two key/value pairs.
'eventValue':rank 'event':'RankTracker'
should be
'eventValue':rank, 'event':'RankTracker'
Maybe that's what's causing unexpected results.

javascript use var value as name for new var

How can I use an array key (text value) to reference a variable by that same name?
jsFiddle
var cr,au,gen,bn,fmt,str;
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
"'"+key+"'" = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
In another language, I would simply surround the var name with percent signs, thus:
var %key% = "bob";
Would make:
var cr = bob;
How can this be done in javascript?
Why I require this unusual solution:
A series of AJAX calls are being made to a pre-existing PHP processor file that expects all data in HTML. In this case, I already had the data in JSON/jsObj format and wished to quickly break it out into separate variables. The most efficient/readable (believe it or not!) code was achieved by using eval(). After reading Jonathan's and Niet's posts/comments, I struggled with how to keep the data in JSON format and use it like that, but the AJAX processor always requires one piece of data in HTML format. To my disappointment, I was unable to find a way to mix the two data types. Faced with the choice of re-coding the entire app to use JSON only, or moving ahead with HTML, the SDLC made the decision for me.
Thanks Niet, Jonathan, Cristy, Stephen Thomas and Fallenreaper for sound advice and great ideas. I'll be scoping other posts you've each made.
While you could use eval like this:
// DO NOT DO THIS
eval(key+" = svASCtrls[key];");
You should probably stop and ask yourself why you want to do this in the first place. You already have a very tidy object, so just use it...
You can define your variables as properties of an object
var obj = { cr: null, au: null, gen: null, bn: null, fmt: null, str: null };
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
obj[key] = sbASCtrls[key];
alert('var CR: ' + obj.cr);
return false;
}
As any global variable is a child of the window object, you can create the variable at window[key]
for (var key in sbASCtrls){
alert("key: " + key);
alert("val: " + sbASCtrls[key] );
//This should work, but jsfiddle messes with the window object
window[key] = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
Note that this does not work on jsfiddle, but should work on your website.

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Process hash fragment using JavaScript

i want to get hash parameters value in my java script
for example my url should be like that
www.example.com/#!mydata=data&myopt=option
i want to get mydata in variable which will be "data" as value,
and myopt "option"
iam trying to implement google ajax cowling like here
Google Code
and i have tried to implement jquery address
but with big fail so help me either by solving 1st part or give me simple walk through tutorial to implement jquery address to my ajax requests ,thank you
This piece of code will convert any well formed (i.e. properly url-encoded) request string into an object literal with values parsed.
var s = "#!mydata=data&myopt=option";
var o = {};
$.each(s.substr(2).split('&'), function(i, elem) {
var parts = elem.split('=');
o[parts[0]] = parts[1];
});
Then you can access values like o.myopt
UPDATE
Of course, to get the value from browser's address, you should use
var s = window.location.hash;

Categories

Resources