使用Bottle或Flask将多个页面路由到具有参数的相同模板

问题描述 投票:1回答:1

我想使用参数将多个页面路由到示例模板,并让其他静态文件也自动路由:

@route('/test1')
@route('/hello2')
@route('/page3')
@view('tpl/page.html')
def page():
    context = {'request': request, 'pagename': ??}
    return (context)

@route('/<filename>')
def files(filename):
    return static_file(filename, root='./static/')

我希望page.html显示请求名称:

<div>This is the page that was requested: {{pagename}} </div>

我期待在这里:

This is the page that was requested: hello2

如何将多个页面定向到同一个模板,并且可以访问页面名称?

我尝试了str(request).split('example.com/')[1].replace('>', ''),但这是一个肮脏的黑客,我想有一个更清洁的方式从test1获得hello2@route等。

python bottle
1个回答
1
投票

你可以这样做:

@route('/test1', route_name='test1')
@route('/hello2', route_name='hello2')
@route('/page3', route_name='page3')
@view('tpl/page.html')
def page(route_name):
    context = {'request': request, 'pagename': route_name}
    return (context)

Flask会自动将不匹配的参数传递给您的路线。

© www.soinside.com 2019 - 2024. All rights reserved.