2013-07-10 33 views
0

我在我用來存儲值列表的MongoDB集合中有「影響」字段。看起來是這樣的:如何在jinja2模板中打印MongoDB列表?

{ 
    "_id" : ObjectId("51dc89712ef6af45b0a5f286"), 
    "affects" : [ 
     "GS", 
     "WEB", 
     "DB", 
     "CB", 
     "ALL", 
     "OTHER" 
    ], 
} 

而且在模板(HTML頁)我這樣做:

{% for change in changes %} 
{{ change._id }} 
{{ change.affects }} 
{% endfor %} 

這工作完全在你的領域只有一個值,例如_id想這在輸出我HTML頁面:

51dc89712ef6af45b0a5f286 

當雖然有多個值,輸出出來是這樣的:

[u'GS', u'WEB', u'DB', u'CB', u'ALL', u'OTHER'] 

在jinja2中有一種方法可以遍歷值列表並將它們打印出來而沒有括號,引號和u?

謝謝。

回答

3

你可能需要在神社嵌套循環,試試這個:

{% for change in changes %} 
    {{ change._id }} 
    {% for affect in change.affects %} 
     {{ affect }} 
    {% endfor %} 
{% endfor %} 
+0

啊,我嘗試過類似的東西,但我的語法錯了。它與你的工作。非常感謝你。 – admiralobvious

1

我是有類似的東西,我修復... 燒瓶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) 

然後你jinja模板可能看起來像這樣... mongo_index.hmtl

{% for i in blog_info %} 
    {{ i['url'] }} 
    {{ i['post'] }} 
{% endfor %} 

最初的對象從MongoDB中看起來像這樣回到...

[{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')}] 

我花了一段時間才能弄清楚,我想,如果它看起來像一個列表,實際上它並不意味着它是一個。 :)