Skip to content Skip to sidebar Skip to footer

Flask|jinjia2|javascript: Passing Flask Template Variable Into Javascript

What is the best way to pass a variable from a Flask template into the Javascript file? Here is my code I have a simple view in my webapp: @webapp.route('/bars') def plot_d3_bars()

Solution 1:

Well, maybe it is too late, but here we go.

When you use a JavaScript code embedded in HTML code, this script will be rendered together with HTML. So any variable referenced in JavaScript, as a Flask variable, will be available in the page rendered.

When you use an external JavaScript file linked in HTML code, its code already exists, before the HTML be rendered. In some cases, I may say most of them, you aren't the owner of this file. So any variable referenced in JS file will not be rendered.

You may put this variable in HTML, via JS code, and consume this data with functions from foreign JS file.

Or you can render this JS file, before render the template, and use it. But I strongly recomend not to use this approach.

Post a Comment for "Flask|jinjia2|javascript: Passing Flask Template Variable Into Javascript"