@app.route('/add-company', methods=['POST', 'GET'])
def comp():
data = []
for x in company.find({},{"companyname": 1, "_id": 0 }):
data.append(x)
return render_template('home/add-company.html', data=json.dumps(data))
So I have this python code to send company names from MongoDB to jinja2 in JSON format and the template renders it like below
[{"companyname": "Test"}, {"companyname": "ff"}, {"companyname": "tpms"}]
Now I tried
{% for list in data %}
<option>{{ list }}</option>
{% endfor %}
But the template renders it like this
[
{
c
o
m
p
a
n
y
.
.
.
Which is the issue here I want it to populate my dropdown list like this:
<option>Test</option>
<option>ff</option>
<option>tpms</option>
Please suggest the solutions which I should follow! Thanks in advance!
CodePudding user response:
Don't dump the json data as string.
- return render_template('home/add-company.html', data=json.dumps(data))
return render_template('home/add-company.html', data=data)
Also you probably want to do something like
{% for val in data %}
<option>{{ val['companyname'] }}</option>
{% endfor %}
CodePudding user response:
Need to send the whole array of data into the template:
return render_template('home/add-company.html', data=data)
And then iterate over it and access the specific value:
Data: [{"companyname": "Test"}, {"companyname": "ff"}, {"companyname": "tpms"}]
After we iterate:
{% for val in data %}
<option>{{ val['companyname'] }}</option>
{% endfor %}
result:
Test
ff
tpms