0

With this line of code in python I created JSON containing multiple messages:

notification = [{
                 'message': 'This is the homepage',
                 'username': 'User',
                 'room': 'Home',
                 'timestamp': '11:59' 
                },
                {
                 'message': 'Hello World!',
                 'username': 'User',
                 'room': 'Home',
                 'timestamp': '12:00'
               }]

return render_template("chat.html",  messages = notification)

Now I would like to print all the messages on the webpage, so I sent all the information to javascript. But when the output of the following script returns an empty string.

const message = `{{messages}}`;
console.log(message);

Why is the string empty?

6
  • It seems like you are passing a list and then using it as a string in JS. Try changing that and post the ouput Commented Apr 25, 2020 at 23:00
  • 3
    Is this Flask? Is the js code embedded in the html file? Commented Apr 25, 2020 at 23:04
  • Yeah it is. render_template is a flask function. I don't know about the rest of the file. Also the script is probably embedded into the HTML. I just assumed it was, my bad. Commented Apr 25, 2020 at 23:08
  • Yes it is indeed a flask function and the script is embedded in the HTML Commented Apr 25, 2020 at 23:10
  • Can you try without the quotes around {{messages}}? Commented Apr 25, 2020 at 23:14

2 Answers 2

2

What you are passing in the notification variable isn't actually JSON, it's a Python list. You need to use json.dumps to convert it to an actual JSON string.

Then in your JS you will need to wrap the string in quotes (single quotes best as JSON uses double quotes) so that your JS is syntactically valid. You can then even use Javascript's JSON.parse to convert it to a JS array:

const message = '{{messages}}' ;
console.log(JSON.parse(message) );
Sign up to request clarification or add additional context in comments.

Comments

0

Try passing the notification as json to the template

Flask

return render_template("chat.html",  messages = json.dumps(notification))

Template

const message = JSON.parse('{{messages | tojson | safe}}');
console.log(message)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.