Skip to content Skip to sidebar Skip to footer

How To Access External Javascript Files Through Jinja[flask]?

I wanna know whether i can access external javascript files through jinja? It's working well with html files or with js embedded in html files but not when javascript file is exter

Solution 1:

You need to understand how Jinja works. When you run the commmand return render_template('main.html', var1 = 1, var2 = 2), it gets processed in the following way:

  1. The Flask server opens the main.html template
  2. Renders/replaces all the defined Jinja variables i.e. the context into the template
  3. Sends the rendered HTML to the client.

Hence the variables are not loaded into the {{ var }} place-holders on the client side but at the server side.

Therefore to achieve what you are trying to do you could do something as follows: In main.html code:

<html><body><p>The first value is {{var1}}</p><script>var var2 = {{var2}};
        <scriptsrc="main.js"></script></body></html>

In main.js code:

window.onload=function(){
    console.log(var2);
};

Note: We have added the script inside HTML code before calling main.js which the dependent script.

Let me know if this solves your issue and you have understood the explanation.

Solution 2:

TLDR; Pass your flask variable to a global JS variable from your HTML file.

I don't think that it's possible to access external JavaScript files directly from Flask. But you can use this hack, it works with many templating languages (Jinja, EJS...)

main.py:

@app.route('/')defdefault():
    return render_template('main.html', var1 = 1, var2 = 2)

main.html

<html><body><p>The first value is {{var1}}</p><!-- Insert this <script/> tag before loading you main.js --><scripttype="text/javascript">window.myVar1 = "{{var1}}"</script><scriptsrc="main.js"></script></body></html>

main.js

window.onload=function(){
    // Now you can access to myVar1 directlyconsole.log(myVar1);
};

Post a Comment for "How To Access External Javascript Files Through Jinja[flask]?"