从Jinja表达式中调用的函数中的dict访问值

时间:2016-03-18 17:32:15

标签: python flask jinja2

我将一个dict从Flask视图传递给Jinja模板。我可以在dict中渲染值,但如果我尝试将它们传递给url_for,我会得到UndefinedError: 'dict object' has no attribute 'eId'。为什么第一次成功时第二次访问失败?

@app.route('/')
def show_entries():
    if session.get('logged_in'):
        cur = g.db.execute('select title, text, id from entries1 WHERE userid = ? OR public = 1 order by id desc', [userInfo['userid']])
    else:
        cur = g.db.execute('select title, text, id from entries1 WHERE public = 1 order by id desc')
    entries = [dict(title=row[0], text=row[1], eId=row[2]) for row in cur.fetchall()]
    return render_template('show_entries.html', entries=entries)
{% for entry in entries %}
    This works: {{ entry.eId }}
    This errors: {{ url_for('delete_entry', btnId=entry.eId) }}
{% endfor %}

2 个答案:

答案 0 :(得分:1)

而不是"{{ url_for('delete_entry', btnId= entry.eId) }}"您应该"{{ url_for('delete_entry', btnId= entry['eId']) }}",因为字典中的元素应该通过get方法访问。 {{ entry.title }}工作的唯一原因是因为jinja2。

由jinja评估重要{{ entry.title }},而"{{ url_for('delete_entry', btnId= entry.eId) }}"由python评估并休息。

答案 1 :(得分:0)

您的entry是一本字典。虽然Jinja的表达式语法允许您对字典使用属性语法(dict.attr),但只要您使用Python语法将参数传递给函数,就需要使用Python的常规字典访问语法dict['attr']

相关问题