Search code examples
javascriptpythonvisual-studio-codeflaskjinja2

Property assignment expected.javascript when combined to jinja


Using javascript functions on one of my pages in flask, I need to use the jinja variables passed from python.

It actually works well but the thing is that VS Code shows me an error "Property assignment expected.javascript" on the brackets here :

{{ content|tojson }}

The current complete script is :

  function printData (nb) {
    const jsArrayOfItems = {{ content|tojson }};
    var str = JSON.stringify(jsArrayOfItems[nb][1], null, 2);
    document.write(str)
  }

with content a list passed from the python flask route.

I have already seen this post but it seems that I have the same problem than the author, which is that if I use quotation marks jsArrayOfItems becomes an empty value instead of the list.

So if you have any idea about how to avoid this problem I'd be glad someone tell me. Thanks !


Solution

  • In your code, the variable content is regarded as a string, and it is not converted into an effective JavaScript object. You can use the json.parse() function to parse the json string

    Modify the code

    const jsArrayOfItems = {{ content|tojson }};
    

    to

    const jsArrayOfItems = JSON.parse('{{ content|tojson|safe }}');