In Velocity I set a variable like this:
#at ($page.config)
#set ($zip = $helper.xssSafeString($url.param("zip")))
#end
Now I want to access the value of $zip
in a JavaScript file that is included like this:
#at ($page.body)
<script type='text/javascript' src='/javascript/main.js'></script>
//...
#end
In the main.js file I alredy tried the following solutions that I found for example here , but it either detects wrong Syntax or just returns the string "${zip}" as value:
var zip = ${zip};
var zip = $zip;
var zip = "${zip}";
So my question is how to access the value of the velocity variable and assign in to a JavaScript variable in an external file.
Velocity variables are available in velocity templates, you can't use your variables in files that does not go through the template engine. Javascript files does not, unless you specify so.
Since you haven't posted the contents of your main.js
file I will go for a broader example on how you could make it available in your main.js
.
Consider the contents of your main.js
file is:
var APP = APP || {};
APP.core = (function () {
var zip = '';
return {
setZip: function(zip) {
this.zip = zip;
},
getZip: function() {
return this.zip;
}
}
})();
In your velocity file you can then add the following to set the zip
variable in main.js
:
#at ($page.body)
<script type='text/javascript' src='/javascript/main.js'></script>
<script>
APP.core.setZip(${zip});
console.log(APP.core.getZip());
</script>
#end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.