Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 626
sidewinder Avatar asked Apr 02 '11 13:04

sidewinder


2 Answers

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 }
like image 141
Michael Merickel Avatar answered Sep 30 '22 18:09

Michael Merickel


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

like image 38
Rocky Burt Avatar answered Sep 30 '22 17:09

Rocky Burt