rub*_*lex 7 python jinja2 flask
我有一个jinja2模板,我重复使用不同的Flask路线.所有这些路由都只有一个必需参数,只处理GET请求,但有些路由可能有额外的参数.
有没有办法将额外的参数附加到url_for()?
就像是
url_for(my_custom_url, oid=oid, args=extra_args)
Run Code Online (Sandbox Code Playgroud)
将呈现给(取决于路由端点):
# route 'doit/<oid>' with arguments
doit/123?name=bob&age=45
# route 'other/<oid>' without arguments
other/123
Run Code Online (Sandbox Code Playgroud)
我的用例是提供预定义查询参数的链接:
<a href=" {{ url_for('doit', oid=oid, args=extra_args }} ">A specific query</a>
<a href=" {{ url_for('other', oid=oid) }} ">A generic query</a>
Run Code Online (Sandbox Code Playgroud)
我想在没有JavaScript的情况下运行这个模板,所以如果可能的话,我不想分配一个点击监听器并使用AJAX来GET为每个链接做一个请求.
任何与路由参数不匹配的参数都将添加为查询字符串.假设extra_args是一个字典,只需打开包装即可.
extra_args = {'hello': 'world'}
url_for('doit', oid=oid, **extra_args)
# /doit/123?hello=world
url_for('doit', oid=oid, hello='davidism')
# /doit/123?hello=davidism
Run Code Online (Sandbox Code Playgroud)
然后在视图中访问它们request.args:
@app.route('/doit/<int:oid>')
def doit(oid)
hello = request.args.get('hello')
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6990 次 |
| 最近记录: |