简体   繁体   English

如何将 Python 变量/Jinja2 模板传递给 JavaScript 文件?

[英]How to pass a Python variable/Jinja2 template to a JavaScript file?

I know you can pass a variable to inline javascript in your html like in this question :我知道您可以将变量传递给 html 中的内联 javascript ,就像在这个问题中一样:

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

But how can I pass this data to a function in a javascript file?但是我怎样才能将这些数据传递给 javascript 文件中的 function 呢?

I want to call test_func({{ data|safe }}) from the file:我想从文件中调用test_func({{ data|safe }})

    <script src="{{ url_for('static', filename='scripts/highcharts.js') }}"></script>

If your js code uses a module system there are more elegant ways to do this, but otherwise this is one way, if I understand your situation correctly:如果您的 js 代码使用模块系统,则有更优雅的方法可以做到这一点,但如果我正确理解您的情况,这是一种方法:

<div>blah blah</blah>
<script>
    var window.myData = window.myData = {{ data|tojson }};
</script>

... It sounds like from your comments that you are modifying highcharts.js , which I would have expected would be an unmodifiable 3rd party file. ...从您的评论中听起来您正在修改highcharts.js ,我原以为这将是一个不可修改的第 3 方文件。 But assuming you can modify it, within highcharts.js would be something like:但是假设你可以修改它,在highcharts.js中会是这样的:

test_func(window.myData);

This assumes that your myData is safe to share globally across all js on your page.这假设您的myData可以安全地在您页面上的所有 js 中全局共享。

Also note that for this to work, you have to make sure window.myData has been populated before highcharts.js is run.另请注意,要使其正常工作,您必须确保在window.myData运行之前已填充highcharts.js You should not rely on asynchronous happenstance for this but instead make that sure the code is always loaded in the right order based on js loading rules.您不应为此依赖异步偶然事件,而应确保始终根据 js 加载规则以正确的顺序加载代码。 This is another thing that using js modules of some flavor would take care of.这是使用某种风格的 js 模块可以解决的另一件事。

Note on escaping:关于 escaping 的注意事项:

Note that I've used tojson instead of safe here.请注意,我在这里使用tojson而不是safe That's a result of 3 minutes of googling and may be wrong.这是 3 分钟谷歌搜索的结果,可能是错误的。 But the point is that I don't think safe is what you want probably, which seems to turn off escaping entirely.但关键是我认为safe可能不是你想要的,这似乎完全关闭了 escaping。 Unless you know with confidence that data is free from potential XSS-style attack strings, you probably want javascript escaping here I think instead of HTML escaping which is probably the default. Unless you know with confidence that data is free from potential XSS-style attack strings, you probably want javascript escaping here I think instead of HTML escaping which is probably the default. However, I'm not an expert.不过,我不是专家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM