在 Flask 中为 url_for 创建动态参数
Create dynamic arguments for url_for in Flask
我有一个 jinja2 模板,我将其重复用于不同的 Flask 路由。所有这些路由都有一个必需的参数并且只处理 GET
个请求,但有些路由可能有额外的参数。
有没有办法将额外的参数附加到 url_for()
上?
类似
url_for(my_custom_url, oid=oid, args=extra_args)
将渲染到(取决于路由端点):
# route 'doit/<oid>' with arguments
doit/123?name=bob&age=45
# route 'other/<oid>' without arguments
other/123
我的用例是为 link 提供预定义的查询参数:
<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>
我想 运行 这个模板没有 JavaScript,所以我不想分配点击侦听器并使用 AJAX 做一个 GET
请求每个 link 如果可能的话。
任何与路由参数不匹配的参数都将添加为查询字符串。假设 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
然后在视图中使用 request.args
:
访问它们
@app.route('/doit/<int:oid>')
def doit(oid)
hello = request.args.get('hello')
...
使用你的例子,如果你事先知道你的参数,这个伤口会像你请求的那样生成 URL。
<a href=" {{ url_for('doit', oid=oid, name='bob', age=45 }} ">A specific query</a>
<a href=" {{ url_for('other', oid=oid) }} ">A generic query</a>
如果您的参数集直到运行时才知道并且存储在字典中,那么@davidism 的答案将是首选。
我有一个 jinja2 模板,我将其重复用于不同的 Flask 路由。所有这些路由都有一个必需的参数并且只处理 GET
个请求,但有些路由可能有额外的参数。
有没有办法将额外的参数附加到 url_for()
上?
类似
url_for(my_custom_url, oid=oid, args=extra_args)
将渲染到(取决于路由端点):
# route 'doit/<oid>' with arguments
doit/123?name=bob&age=45
# route 'other/<oid>' without arguments
other/123
我的用例是为 link 提供预定义的查询参数:
<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>
我想 运行 这个模板没有 JavaScript,所以我不想分配点击侦听器并使用 AJAX 做一个 GET
请求每个 link 如果可能的话。
任何与路由参数不匹配的参数都将添加为查询字符串。假设 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
然后在视图中使用 request.args
:
@app.route('/doit/<int:oid>')
def doit(oid)
hello = request.args.get('hello')
...
使用你的例子,如果你事先知道你的参数,这个伤口会像你请求的那样生成 URL。
<a href=" {{ url_for('doit', oid=oid, name='bob', age=45 }} ">A specific query</a>
<a href=" {{ url_for('other', oid=oid) }} ">A generic query</a>
如果您的参数集直到运行时才知道并且存储在字典中,那么@davidism 的答案将是首选。