I've read up on using different renderers or overriding renderer but I'm wondering if there's a better way to handle this pattern.
Right now, in my view I'm returning a set of items to the template:
@view_config(
route_name = 'name',
permission = 'perm',
renderer = 'r.mako'
)
def r( request ):
items = get_items()
return { 'items': items }
Now I want the ajax version to just renderer a subset of it, also with some data. My current working code:
@view_config(
route_name = 'name',
permission = 'perm',
renderer = 'r.mako'
)
def r( request ):
items = get_items()
if ajax:
return Response( to_json( {
'data1': 1,
'data2': 2,
'data3': 3,
'html': renderers.render( 'shortr.mako',
{ 'items': items },
request )
} )
return { 'items': items }
I guess specifically I wonder if there's a cleaner way to override the renderer and then wrap it in something, without explicitly calling render and making sure I got the dict right or request as a param. thanks
I would suggest using 2 views which properly allow you to apply a different "look-and-feel" (responses) to the same data.
def get_items(request):
return {} # values that you can pick and choose from in each view
@view_config(route_name='name', permission='perm', xhr=True, renderer='json')
def r_ajax(request):
items = get_items(request)
return {
'data1': 1, 'data2': 2, 'data3': 3,
'html': renderers.render('shortr.mako', {'items': items}, request),
}
@view_config(route_name='name', permission='perm', renderer='r.mako')
def r_html(request):
items = get_items(request)
return items
If you're afraid of repeating things for the view configuration, Pyramid 1.3 comes with a cool new feature on its class-based views:
@view_defaults(route_name='name', permission='perm')
class R(object):
def __init__(self, request):
self.request = request
self.items = # ...
@view_config(xhr=True, renderer='json')
def ajax(request):
return {
'data1': 1, 'data2': 2, 'data3': 3,
'html': renderers.render('shortr.mako', {'items': items}, request),
}
@view_config(renderer='r.mako')
def html(request):
return self.items
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