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

Time:05-03

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:

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.

CodePudding user response:

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>
  • Related