访问JavaScript文件中的速度变量 [英] Access Velocity Variable in JavaScript File

查看:144
本文介绍了访问JavaScript文件中的速度变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Velocity中,我像这样设置一个变量:

In Velocity I set a variable like this:

 #at ($page.config)
    #set ($zip = $helper.xssSafeString($url.param("zip")))
 #end

现在,我想访问包含在这样的JavaScript文件中的$zip的值:

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

我在main.js文件中尝试了以下找到的解决方案,例如此处,但是它要么检测到错误的语法,要么只是返回字符串"$ {zip}"作为值:

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}";

所以我的问题是如何访问速度变量的值并将其分配给外部文件中的JavaScript变量.

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变量在速度模板中可用,您不能在未通过模板引擎的文件中使用变量.除非您指定,否则Javascript文件不会.

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.

由于您尚未发布main.js文件的内容,因此我将举一个更广泛的示例,说明如何在main.js中使用该文件.

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.

考虑main.js文件的内容为:

var APP = APP || {};

APP.core = (function () {

    var zip = '';

    return {

        setZip: function(zip) {
            this.zip = zip;
        },

        getZip: function() {
            return this.zip;
        }
    }

})();

然后在速度文件中添加以下内容,以在main.js中设置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

这篇关于访问JavaScript文件中的速度变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆