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
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'
:
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.
来源:https://stackoverflow.com/questions/8573149/easy-way-to-switch-between-renderers-within-the-same-view-method