【问题标题】:Get current, requested URL in Bottle在 Bottle 中获取当前请求的 URL
【发布时间】:2016-09-14 04:35:41
【问题描述】:

我想在我的基本模板中放一些代码块,但只放if request.route is '/page'

我正在尝试添加一些类似的内容:

% if request.route == "/home":
  <a class="pure-button" id="showWishboneAddForm">
    <i class="fa fa-plus-circle"></i> Dodaj tuleję
  </a>
% end

但后来我得到了错误: NameError("name 'request' is not defined",)

我不想在所有路由中添加 request 参数

【问题讨论】:

    标签: templates bottle


    【解决方案1】:

    您可以通过以下简单*方式简单地使请求在所有视图/模板上可用

    from bottle import view, request, template, get
    from functools import partial
    view = partial(view, request=request)
    template = partial(template, request=request)    
    
    #now lets use it
    @get("/")
    @view("mytpl.tpl")
    def index():
        return {"msg": "Cool stuff!"}
    

    我希望它能满足你的需要

    【讨论】:

    • 谢谢!另外我发现了类似的东西:SimpleTemplate.defaults["request"] = request
    • 你不应该这样做,因为这不是线程安全的。您可能在模板中有一个带有错误“请求”变量的页面。
    • @AugustinLaville - request 对象使用 thread.local 所以应该没问题。
    • 我确定不是,做测试。
    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多