问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/40042449/access-velocity-variable-in-javascript-file