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.
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 }
If instead you are hoping for some "global bag" where you can stuff variables that will be available to every template, then your question about IBeforeRender is appropriate.
from pyramid.events import subscriber
from pyramid.events import BeforeRender
@subscriber(BeforeRender)
def add_global(event):
event['name'] = 'Pyramid Developer'
There is an alternative way of adding globals when setting up the Configurator as well. You can see the full info at: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#using-the-before-render-event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With