Reputation: 627
I have the 'affects' field in my MongoDB collection that I use to store a list of values. Looks like this:
{
"_id" : ObjectId("51dc89712ef6af45b0a5f286"),
"affects" : [
"GS",
"WEB",
"DB",
"CB",
"ALL",
"OTHER"
],
}
And in the template (html page) I do this:
{% for change in changes %}
{{ change._id }}
{{ change.affects }}
{% endfor %}
This works perfectly when your field has only one value, for example _id would output like this in my HTML page:
51dc89712ef6af45b0a5f286
When there's multiple values though, the output comes out like this:
[u'GS', u'WEB', u'DB', u'CB', u'ALL', u'OTHER']
Is there a way in jinja2 to iterate over the list of values and have them printed out without the brackets, quotes and u?
Thank you.
Upvotes: 1
Views: 3568
Reputation: 665
I was having trouble with something similar, my fix... flask app.py
@app.route('/mongo', methods=['GET', 'POST'])
def mongo():
# connect to database
db = client.blog
# specify the collections name
posts = db.posts
# convert the mongodb object to a list
data = list(posts.find())
return render_template('mongo_index.html', blog_info=data)
Then your jinja template might look something like this... mongo_index.hmtl
{% for i in blog_info %}
{{ i['url'] }}
{{ i['post'] }}
{% endfor %}
The initial object returned from mongodb looking something like this...
[{u'category': u'python', u'status': u'published', u'title': u'working with python', u'url': u'working-with-python', u'date': u'April 2012', u'post': u'some blog post...', u'_id': ObjectId('553b719efec0c5546ed01dab')}]
It took me a while to figure out, I guess if it looks like a list, it doesn't actually mean it is one. :)
Upvotes: 1
Reputation: 7822
You probably need a nested loop in Jinja, try this:
{% for change in changes %}
{{ change._id }}
{% for affect in change.affects %}
{{ affect }}
{% endfor %}
{% endfor %}
Upvotes: 4