1

I know you can pass a variable to inline javascript in your html like in this question:

<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?

I want to call test_func({{ data|safe }}) from the file:

    <script src="{{ url_for('static', filename='scripts/highcharts.js') }}"></script>
koopmac
  • 936
  • 10
  • 27
  • 1
    I don't think there is a way to do this. You just put the data somewhere that the js code can get it. But in this case since it's a 3rd party library it probably depends on the code. – xdhmoore May 10 '20 at 05:29
  • The issue is that the data I need to pass it is being queried from the database so I can't put it in the js code. The function I'm calling in `highcharts.js` is my own function in the static folder, not a 3rd party library. – koopmac May 10 '20 at 05:35
  • I've written out an answer, but I suspect that maybe I'm not understanding some of the details so let me know if my answer misses something. – xdhmoore May 10 '20 at 23:26

1 Answers1

2

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:

<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. But assuming you can modify it, within highcharts.js would be something like:

test_func(window.myData);

This assumes that your myData is safe to share globally across all js on your page.

Also note that for this to work, you have to make sure window.myData has been populated before highcharts.js is run. 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. This is another thing that using js modules of some flavor would take care of.

Note on escaping:

Note that I've used tojson instead of safe here. That's a result of 3 minutes of googling and may be wrong. But the point is that I don't think safe is what you want probably, which seems to turn off escaping entirely. 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.

xdhmoore
  • 8,935
  • 11
  • 47
  • 90