0

I have followed this post to send data from flask to a JS file.

Flask:

@app.route('/')
def home():
    content = "Hello"
    return render_template('index.html', content=content)

HTML

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <script src='static/app.js'></script>
    <meta id="my-data" data-name="{{content}}">
</body>

JS/JQuery

var djangoData = $('#my-data').data();

I have also tried var djangoData = $('#my-data').data('content'); Nonethless, I get:

typeof djangoData
    "undefined"

In the console.

I was also curious to know if this method is still considered as best practice, if not what is, as I know there are many ways of sending data from FLASK to JS.

Thanks :)

1 Answers1

0

var requiredData = document.getElementById("my-data").getAttribute("data-name") will give you the data you are looking for

HArdRe537
  • 116
  • 5
  • Thank you so much!! Would you recommend this approach? cause I heard it overfloods the HTMl and can raise security concerns. –  Oct 20 '20 at 23:01
  • 1
    if you are using modern frontend frameworks and doing a mix of server side rendering using jinja and the required data loads using api calls within the same page, it would do fine since it will do incremental loading. however if you go for jquery or pure javascript, since entire html rendering will happen on the updation, then it might not be recommended – HArdRe537 Oct 22 '20 at 04:10