1

Variables can be passed between flask and javascript in the following way.

Python

return render_template(foo.html,input_from_python=data) 

Javascript

let var_from_python = {{ input_from_python | tojson }}; 

However, if the notation for flask is included, Typescript cannot be compiled.

Typescript

const var_from_python = {{ input_from_python | tojson }}; 

Can you tell me how to do it better?

4 Answers 4

2

You could have var_from_python served from a different endpoint then fetch it in your typescript file.

@app.route("/your-json-data") def serve_input_from_python: return your_json; 

and simply parse it in TS as so:

const var_from_python = await fetch("yourdomain/your-json-data") .then((response) => response.json()) 

You could also have typescript reference the variable but declare it within javascript in your HTML file or another javascript file but you'd have to jump through other hoops for that.

Sign up to request clarification or add additional context in comments.

Comments

2

flask

from flask import Flask, jsonify, render_template app = Flask(__name__) @app.route('/data') def get_data(): data = {'name': 'John', 'age': 30} return jsonify(data) @app.route('/') def index(): return render_template('index.html') 

Typescript

fetch('/data') .then(response => response.json()) .then(data => { const name: string = data.name; const age: number = data.age; console.log(name, age); }) .catch(error => console.error(error)); 

Comments

0

Your input from Python could be a json string and then on Typescript you should parse to object.

const var_from_python = json.parse("{{ python_input_json }}") 

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
One mistake this has is the use of " instead of `. JSON already uses " so this would break.
0

So Flask does have a way to do this, but it's kind of hacky and took forever for me to finally find and figure out the solution- I was having this problem too.

There's 3 parts to this:

  1. Get the dictionary information in Python
  2. Embed the data into your webpage
  3. Access that data from your JavaScript/TypeScript code

Step 1

Setup the Python dictionary for external use

Somewhere in your Flask code in either the __init__.py file, the routes.py file, or some other similarly accessible file, have the following setup:

input_from_python = {"some":"random data"} @server.context_processor def inject_data() -> dict: # .context_processor information: https://stackoverflow.com/a/43336023/8705841 flask_data = {'all', 'the', 'python', 'variables', 'you', 'want', 'in', 'your', 'js_or_ts', 'input_from_python'} # Create a dictionary from a list of variables: https://stackoverflow.com/a/9496018/8705841 return {'flask_data': dict(((k, eval(k)) for k in flask_data))} 

The @server part should match the name of your Flask app variable (instantiated with server = Flask(__name__)) and does not particularly matter (usually it's called app). The flask_data dict/list should have all the Python variables you want ported over to the front end, but with quotes around them- the eval part of the return will grab the Python variable that matches the input string k.

Step 2

Make the data available on the webpage

In your index.html page, inside the <head> tag (next to your other <script> tags, have this tag as well:

<head> <!-- a whole bunch of stuff --> <!-- get all the Flask variables from Python -> TypeScript --> <script id=flask_data type="text/json">{{ flask_data|tojson }}</script> <!-- possibly a whole bunch more stuff --> </head> 

Basically every single StackOverflow post even mentioning Flask has the above copy-pasted.

Step 3

Access the data from any of your JavaScript files

This is the part that no one else talked about- actually using your data from within your JavaScript (or TypeScript) code, regardless of your directory setup. It's a little hacky, but basically you access the HTML element that has your embedded data and then parse it for use in your program however you want. This is technically TypeScript code, but should work for both JavaScript and TypeScript (it took a ton of trial and error to finally get it to work on my TypeScript build).

foo() { const flask_data = JSON.parse((document.querySelector('#flask_data') as HTMLElement).textContent || ""); this.version = flask_data.version const input_from_python = flask_data.input_from_python; console.log("Data: " + flask_data); console.log("Variable: " + input_from_python); console.log("Running verison '" + this.version + "'"); if (input_from_python === "some value") { do_something(); else { do_something_else(); return input_from_python; } } // the rest of your program, using any part of the flask_data dictionary however you need // . // . // . 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.