Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Value passed from flask to JS works in html, not in static

I need to call a javascript function say_hello which exists in static folder and pass Hello as a message to be displayed as an alert. Here’s what I do:

app.py

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello():
    return render_template('index.html', data={'message': 'Hello'})


if __name__ == '__main__':
    app.run()

This works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    const message = {{data.message|tojson|safe}}
        alert(message);
</script>
</body>
</html>

This doesn’t work:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="/js/hello.js">
    const message = {{data.message|tojson|safe}}
        say_hello(message);
</script>
</body>
</html>

hello.js

function say_hello(message){
    alert(message)
}

The JS console doesn’t show any issues, and the message is not displayed, just a blank page.

>Solution :

When a <script> tag has a src, its contents are ignored. One or the other.

<script src="/js/hello.js">
</script>
<script>
    const message = {{data.message|tojson|safe}}
        say_hello(message);
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading