Access Velocity Variable in JavaScript File

别说谁变了你拦得住时间么 提交于 2020-01-06 15:49:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!