jbuddy_13
jbuddy_13

Reputation: 1276

JS access to python variables via flask {{ variable }} format not working

python:

import json
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
encoded_posts = json.dumps(posts)

javascript:

let obj = {{ encoded_posts }};

JS error logged in console:

Uncaught SyntaxError: Unexpected token ';'

Here are the page according to the CONSOLE. It seems to be losing(?) the {{encoded_posts}}.

<!DOCTYPE html>
<html>
  <head>

      <title>Flask Blog - About</title>

  </head>
  <body>
    <h1>About page!</h1>
    <script>
      let text = document.getElementsByTagName('h1')[0];
      text.addEventListener('click',function(){
        text.style.color = 'red';
      });

      let obj = ;
      let jsonPosts = JSON.parse();
      console.log(jsonPosts);

    </script>
  </body>
</html>

What's happening?

Upvotes: 0

Views: 31

Answers (1)

sc0rp1on
sc0rp1on

Reputation: 368

Have you tried doing:

let obj = JSON.parse('{{ encoded_posts }}');

Upvotes: 1

Related Questions