【问题标题】:Include variables in template context on every page with Bottle.py使用 Bottle.py 在每个页面的模板上下文中包含变量
【发布时间】:2012-04-03 07:29:14
【问题描述】:

在 Flask 中是否有与您获得的上下文处理器等效的 bottle.py?

【问题讨论】:

    标签: python templates flask bottle


    【解决方案1】:

    使用来自 Helgiprevious answer,我使用这个钩子来制作一个 类似 的上下文处理器(瓶子 0.12.x):

    import bottle
    
    
    @bottle.hook('before_request')
    def _context_processor():
        bottle.SimpleTemplate.defaults['foo'] = 'F00'
        bottle.SimpleTemplate.defaults['bar'] = 'B@R'
    

    【讨论】:

      【解决方案2】:

      注意:同样的解决方案可以与其他模板引擎一起使用。该技术完全相同,但您使用 BaseTemplate(它适用于所有模板类)或您要使用的引擎的类。

      【讨论】:

        【解决方案3】:

        如果您使用带有 SimpleTemplate 的香草瓶,我偶然发现了一个解决方案。

        对于我的网站,我需要访问每个模板中的一些功能,app.get_url 显然是其中之一。这对我有用:

        # after app creation, but before the views
        SimpleTemplate.defaults["get_url"] = app.get_url
        SimpleTemplate.defaults["url"] = lambda: request.url
        SimpleTemplate.defaults["fullpath"] = lambda: request.fullpath
        SimpleTemplate.defaults["sorted"] = sorted
        

        这适用于 Bottle 0.9,我没有在框架的更新版本上进行测试。

        此行为未记录在案,但 Marcel Hellkamp 在 this thread 中对其进行了解释。其中还提到了其他解决方案:

        • 传递 _vars 或类似模板 arg 中的全局变量。
        • 创建一个装饰器来提供默认值。

        另外,在 Bottle 0.10 中,SimpleTemplate 模板命名空间中引入了与该问题相关的新函数:defined, get, and setdefault

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-07
          • 2016-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多