问题描述
我正在将字典从烧瓶视图传递给Jinja模板.我可以在dict中呈现值,但是如果我尝试将它们传递给url_for
,则会得到UndefinedError: 'dict object' has no attribute 'eId'
.为什么第一次访问成功后第二次访问失败?
I'm passing a dict from a Flask view to a Jinja template. I can render the values in the dict, but if I try to pass them to url_for
I get UndefinedError: 'dict object' has no attribute 'eId'
. Why did the second access fail when the first succeeded?
@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 %}
推荐答案
您的entry
是字典.虽然Jinja的表达式语法允许您对字典使用属性语法(dict.attr
),但是一旦将参数传递给具有Python语法的函数,则需要使用Python的常规字典访问语法dict['attr']
.
Your entry
is a dictionary. While Jinja's expression syntax allows you to use attribute syntax (dict.attr
) for dictionaries, as soon as you're passing an argument to a function with Python syntax you need to use Python's normal dictionary access syntax, dict['attr']
.
这篇关于从Jinja表达式中调用的函数中的字典访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!