python - 使用 Bottle 或 Flask 将多个页面路由到同一个模板,并带有参数

标签 python bottle

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

@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('>', '') 但这是一个肮脏的黑客,我想有一个从 @route 获取 test1hello2 等的更简洁的方法。

最佳答案

你可以这样做:

@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 会自动将不匹配的参数传递给您的路由。

关于python - 使用 Bottle 或 Flask 将多个页面路由到同一个模板,并带有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49098792/

相关文章:

python - 在 Python 中插入包含到 Bottle 应用程序的特定路径的文件夹

python - 如何在 Pandas 中扩展和创建以下数据集

python PIL : How to draw an ellipse in the middle of an image?

python - 为什么 value_counts 不显示所有存在的值?

python - 如何正确使用 Jinja2 计数/长度而不会出错?

python - 在for语句中,我能够得到预期的结果。但是为什么我用while语句却得不到预期的结果呢?

python-3.x - 使用 Bottle.py 提供嵌套的静态文件

python - RavenDB对象已正确保存,但查询时有一些空属性

python - Pandas 数据框,NAN 上的 cumsum 重置

python - Heroku R10 启动超时错误