0

In a flask app I pass the length of a dataframe to the html

return render_template("causes.html",vid=vid,dflength=dflength)

the html gets the value of dflength inside a script (named myscript below) without any problem.

<script>
var dflength = {{ dflength|safe }};
...
</script>

However when I try to move the above script from the html to a separate js file the double curly braces give an error Uncaught SyntaxError: Unexpected token {

<script src="/static/javascript/myscript.js" type="text/javascript"></script>

The last attempt I tried adding parentheses ({{ dflength|safe }}) without any luck... any ideas as to why this works inline but not in a separate js file? Jslint just tells me Expected an identifier and instead saw '{'.

JC23
  • 1,248
  • 4
  • 18
  • 28
  • ended up using answer found [here](https://stackoverflow.com/questions/3412275/loading-external-script-with-jinja2-template-directive) but it loads the entire js function so it's readable... – JC23 Oct 15 '19 at 17:32

1 Answers1

0

I'm not a Flask developer, but maybe the separate JS file doesn't receive variables from Flask before "render" instead of HTML. Mine suggestion to you is never mixing Flask with JS. If you want to use these values from the back-end, you should do a request.

Taymison
  • 1
  • 2
  • hey @Taymison I'm always open to new ways/approaches when it comes to code... can you clarify what you mean by `you should do a request` – JC23 Oct 15 '19 at 17:27
  • I mean an HTTP request with Ajax. I suggest you create API routes and consuming it instead of to print Flask code into JS code. I think that is a better practice. – Taymison Oct 15 '19 at 20:55