Search code examples
javascriptpythonpython-3.xflaskjinja2

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 external.

code:

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

main.html code:

<html>
<body>
        <p>The first value is {{var1}}</p>
        <script src="main.js"></script>
</body>
</html>

main.js file:

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

now the jinja code in main.js is not working

Maybe it's not possible to use it in external js?

If someone can help, please reply to this thread.


Solution

  • 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}};
            <script src="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.