我对 Flask 和 Jinja 比较陌生,我遇到的问题更像是一个"最佳实践"问题,因为我可以用我目前所知道的成功地实现我需要的东西,但它感觉有点笨拙。此外,我还偶然发现了一个我没想到的副作用,我希望能够首先完全避免。
我有一个非常标准的route
定义,它呈现了一个Jinja HTML页面。在此页面上有许多按钮,根据某些预定条件,我想使它们可见。这是我到目前为止创建的:
@app.route('/some/route/')
def index(foo, bar):
button = {
'create': False,
'update': False,
}
if foo:
button['create'] = True
if bar:
button['update'] = True
return render_template('index.html', button=button)
在金贾:
<!-- Somewhere on the page, I might want to show this button -->
{% if button.create %}
<button>Create</button>
{% endif %}
<!-- Somewhere else on the page, I might want to show this other button -->
{% if button.update %}
<button>Update</button>
{% endif %}
乍一看,这应该可以正常工作。但不幸的是,您可能已经发现了这个问题:.update
是一个built-in method update of dict object
,因此尽管我的Create
按钮按预期运行,但我的Update
按钮始终可见。
所以我的想法是:
- 由于对我的按钮名称使用保留字的风险,我将不得不将它们命名为命名空间,也许从
button.update
更改为button.show_update
。我可以做到,但它并不像我想要的那么短和切中要害。 - 我真的不想像
button_create
和button_update
那样单独声明每个按钮,因为那样我必须将每个按钮单独传递给render_template()
这只会很混乱,有大量按钮和其他数据来提供模板。 - 有没有一种更好的方法来处理我不知道的这种情况?还是金贾充满了这些小陷阱?
我尝试过搜索,但没有什么能接近我正在寻找的东西......也许我只是想多了这整件事?...
我使用烧瓶已经有一段时间了,但我会尝试这样的事情。我会去掉你的 python 代码和 jinja 模板中的 2 if 语句。请记住,我对你的应用程序一无所知,但我相信你明白了。 我用了一个其他的,它可能可以用 elif 甚至 bar 交换。任何适合您需求的东西。
@app.route('/some/route/')
def index(foo, bar):
buttons = []
if foo:
buttons.append('create')
if bar:
buttons.append('update')
return render_template('index.html', button = buttons)
在金贾:
{% for button in buttons %}
<button> {button} </button>
{% endfor %}