将python dict传递给模板

GMa*_*rsh 10 python jinja2 flask

必须有办法做到这一点......但我找不到它.

如果我将一个字典传递给模板,如下所示:

@app.route("/")
def my_route():
  content = {'thing':'some stuff',
             'other':'more stuff'}
  return render_template('template.html', content=content)
Run Code Online (Sandbox Code Playgroud)

这在我的模板中工作得很好......但有没有办法可以放弃'内容'.来自

{{ content.thing }}
Run Code Online (Sandbox Code Playgroud)

我觉得我以前见过这个,但在任何地方找不到它.有任何想法吗?

And*_*rey 15

尝试

return render_template('template.html', **content)
Run Code Online (Sandbox Code Playgroud)


geo*_*ock 13

您需要使用**运算符将contentdict作为关键字参数传递:

return render_template('template.html', **content)
Run Code Online (Sandbox Code Playgroud)

这实际上与将dict中的项作为关键字参数传递相同:

return render_template(
    'template.html',
    thing='some stuff',
    other='more stuff',
)
Run Code Online (Sandbox Code Playgroud)