Python: 在 Pyramid 中访问 Renderer Global

Python: Accessing Renderer Global in Pyramid

我想从金字塔中的 mako 模板访问 GMAPS_API_KEY 全局渲染器。我不断收到 GMAPS_API_KEY 未定义的错误消息:

 ...
 File "views/header.html", line 10, in render_body
    <script src="https://maps.googleapis.com/maps/api/js?key=${GMAPS_API_KEY}&sensor=true"></script>
  File "/scratch/temp/venvs/py2.7.10/lib/python2.7/site-packages/mako/runtime.py", line 226, in __str__
    raise NameError("Undefined")
NameError: Undefined

我有 3 个文件(我省略了很多东西):

header.html:

 <script src="https://maps.googleapis.com/maps/api/js?key=${GMAPS_API_KEY}&sensor=true"></script> <!-- ERROR HERE -->

map.mak:

<%include file="header.html"/>

webapp.py

from pyramid.events import subscriber
from pyramid.events import BeforeRender

@subscriber(BeforeRender)
def add_global(event):
    event['GMAPS_API_KEY'] = get_gmaps_key()

def show_map(request):
    return render_to_response('views/map.mak', {},request=request)

config = Configurator()
config.include('pyramid_mako')
config.add_route('map', '/')
config.add_view(show_map, route_name='map')
app = config.make_wsgi_app()
host, port = '127.0.0.1', 8080
server = make_server(host, port, app)
server.serve_forever()

@subscriber 要求您在包含行 @subscriber 的包上调用 config.scan(),或者您需要将装饰器替换为对 config.add_subscriber() 的调用,如下所示在金字塔配置器的文档中:http://docs.pylonsproject.org/projects/pyramid//en/latest/api/config.html#pyramid.config.Configurator.add_subscriber