3

I set up my function like this

@view_config(
    route_name = 'route_name',
    permissions = 'permissions',
    renderer = 'r.mako'
)
def r( request ):
    # stuff goes here

now, I want to add functionality such that I check certain conditions (using ajax) i would use one template, otherwise use another. is there a way to do this in pyramid? thanks

Timmy
  • 12,468
  • 20
  • 77
  • 107

1 Answers1

16

Well you can add the view multiple times with different renderers if you can determine what you want to do via predicates. For example

@view_config(route_name='route', xhr=True, renderer='json')
@view_config(route_name='route', renderer='r.mako')
@view_config(route_name='route', request_param='fmt=json', renderer='json')
def r(request):
    # ...

Or you can just override the renderer manually via request.override_renderer = 'b.mako':

http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/renderers.html#overriding-a-renderer-at-runtime

Or you can just explicitly render the response via the render and render_to_response methods from within the view, as the renderer argument is ignored if you return a Response object from the view.

Note that the xhr predicate in the first example should be sufficient to check for an ajax request. Note also that you don't have to use the same view for both if you don't want to, just depends.

Michael Merickel
  • 23,153
  • 3
  • 54
  • 70
  • Also, the `accept` parameter of `view_config` can be used to render the format requested. For example `@view_config(route_name="route", accept="application/json", renderer="json")`. – Antoine Leclair Dec 20 '11 at 14:58
  • 1
    `accept` is unreliable unless you add it to all of the views in that "group". It is biased by the quality factor in the accept header, so the other view should `accept='text/html'`, or the json one will always be chosen because if you remember most browsers specify `accept='*/*'`. – Michael Merickel Dec 20 '11 at 15:54