在Google App Engine的jinja2中,我如何(轻松)根据带参数的路由名称构建URL?

Jer*_*emy 5 google-app-engine jinja2

如果我构建一个jinja环境如下:

jinja_environment = jinja2.Environment (
    loader=jinja2.FileSystemLoader ((os.path.dirname (__file__), 'templates')), extensions=[])
jinja_environment.globals['url_for'] = webapp2.uri_for
Run Code Online (Sandbox Code Playgroud)

在我的模板中,当路由没有定义任何参数时,我可以从路由名称构建简单的URL:

{{ url_for('user_home') }}
Run Code Online (Sandbox Code Playgroud)

但是,当路由包含由字符串定义的参数时/invoice/<:\d+>,我无法传递任何参数.以下列所有方式调用它会失败,其中包括KeyError "Missing argument "0" to build URI.":

{{ url_for('invoice') }}
{{ url_for('invoice', args=['123']) }}
{{ url_for('invoice', kwargs={'__0__':'123'}) }}
{{ url_for('invoice',_request=None, args=['123'],kwargs={'__0__':'123'}) }}
Run Code Online (Sandbox Code Playgroud)

现有的例子似乎已经过时了 - 至少我无法让它们发挥作用.我错过了什么?

top*_*ess 7

Route('/invoice/<invoice_id>/', handler=invoice_handler, invoice_id='something')

{{ url_for('invoice', invoice_id=123) }}

你可以试试上面的内容,Jinja期待你定义你的处理程序的命名参数.