is there a way to pass a python variable to javascript without writing it to a file?

  • Last Update :
  • Techknowledgy :

Let's say I have a simple Python variable, such as the following:

x = 5

I'd like to create a web page that uses javascript to further process that variable, running on the same computer (a Raspberry Pi).

<!DOCTYPE html>
<html>

<body>

   <script>
      document.write(x);
   </script>

</body>

</html>

Suggestion : 2

Last Updated : 17 May, 2022

Syntax:

pip install js2py

Suggestion : 3

Post date April 3, 2022 ,© 2022 The Web Dev

For instance, in our view, we write

@app.route('/')
def hello():
   data = {
      'username': 'jane',
      'site': 'example.com'
   }
return render_template('settings.html', data = data)

Then in the settings.html template, we write

<html>
    <head>
         <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
         <script type="text/javascript">
            myVar = myFunc({{ data | tojson }})
         </script>
    </head>
</html>