9

I know how to pass a variable from Flask (python) to my template html file with {{data}}. However I am having trouble accessing each dictionary element and its respective key-value pairs in the list in javascript.

start.py

def func1():
        data = filter() #returns a list of dictionaries

    return render_template("template1.html", data=data)

template1.html

<html>
  <head>
  .....
  </head>
  <body>
    <p>This is html: {{data}}</p>

    <script type="text/javascript" src="{{url_for('static', filename='js/add.js') }}"></script>
    <script type="text/javascript">
    myvar = '{{data}}';
    document.write(myvar);

    </script>
  </body>

</html>

add.js

//code to be written here

myvar and This is html: both outputs out the entire list of dictionaries. I've already tried myvar[0] but that just outputs [ for some reason. I have also done:

myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);

but that outputs [object Object].

2 Answers 2

15

By placing data in single quotes you are creating a string. To get python data types into JavaScript, serialize them with {{ data | tojson }}.

var parsed = JSON.parse('{{data | tojson}}');

You may need to escape the output with safe filter. See more at sending data as JSON object from Python to Javascript with Jinja

Sign up to request clarification or add additional context in comments.

1 Comment

single quotes was the important part!
1

Got it!

myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);

Outputs the [object Object] which is the dictionary at the position. So then all you need to do is document.write(parsed[0].name); to access its name value!

3 Comments

Don't use document.write(); You'll often get warnings from the browser about it. Use document.querySelector() or document.getElementById() and set it's .innerText to your parsed[0] value.
Ah, I see. I figured document.write() would be best since I will be using the dict values to create new html elements.
Usually you'd store just data in the json, then loop over it to create elements using document.createElement()

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.