Search code examples
pythonpylonspyramid

Equivalent of template context in Pyramid (pylons user)


What is the equivalent of template context in Pyramid?

Does the IBeforeRender event in pyramid have anything to with this? I've gone through the official documentation but diffcult to understand what the IBeforeRender event is exactly.


Solution

  • Pyramid already provides a tmpl_context on its Request object, so pretty simply you just have to subscribe a BeforeRender event to add it to the renderer globals:

    def add_renderer_globals(event):
        event['c'] = request.tmpl_context
        event['tmpl_context'] = request.tmpl_context
    
    config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')
    

    From now on in your code when you receive a request, you can set parameters on it:

    request.tmpl_context.name = 'Bob'
    

    And subsequently your template may reference the name variable:

    ${ c.name }