On Mon, Dec 13, 2010 at 6:28 AM, Nikolaj <[email protected]> wrote:
> Hi all,
>
> Without the usual Pylons globals, does this look like a sane way to do
> Pylons-style rendering of templates from handlers? Specifically, the
> use of the superclass with self.render and self.c.
>
> N
>
> from pyramid import renderers
>
> class Handler(object):
> def __init__(self, request):
> self.request = request
> self.c = self.request.tmpl_context
>
> def render(self, renderer_name):
> return renderers.render_to_response(renderer_name, {},
> self.request)
>
> class HomeHandler(Handler):
> def index(self):
> self.c.foo = 'bar'
> return self.render('/index.mako')
class Handler(object):
def __init__(self, request):
self.request = request
c = request.tmpl_context
c.stylesheet = request.route_url("stylesheet")
class HomeHandler(Handler):
@action("/index.mako")
def index(self):
return {"foo": "bar"}
# /index.mako
<html><head>
<link rel="stylesheet" type="text/css" href="${c.stylesheet}" />
</head><body>
<p>Foo is ${foo}.</p>
<p>Query param q is ${request.params.get('q', 'UNKNOWN')}.</p>
</body></html>
If you use the 'action' decorator, you don't need 'c' for the
action-specific variables; however, it is still useful for overall
variables set in __init__.
The current paster templates (in Pyramid 1.0a4) register a subscriber
that pushes the expected globals into the template namespace, at least
for 'request', 'tmpl_context', 'c', 'session', and 'url'. At least the
'pylons_sqla' template which I use does this. It's is done by the
following line in 'myapp/__init__.py':
config.add_subscriber(
'pylonssqlaapp.subscribers.add_renderer_globals',
'pyramid.events.BeforeRender')
Note: 'app_globals' and 'cache' are missing because those aren't well
defined in Pyramid yet. 'h' is set to None. And 'url' may change to
'route_url' in a future version, to distinguish from 'model_url'. You
can modify myapp/subscribers.py to specify which variables you want in
every template, to assign 'h' to a helpers module, to rename 'url',
etc.
--
Mike Orr <[email protected]>
--
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en.