Easy way to switch between rendering within the same view method

I set my function as follows

@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 any way to do this in the pyramid? thanks

+1
source share
1 answer

Well, you can add a view several times with different renderers if you can determine what you want to do through the predicates. for instance

 @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 simply override the rendering manually with 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 simply explicitly display the response using the render and render_to_response from the view, since 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 validate the ajax request. Also note that you do not need to use the same view for both, if you do not want it, it just depends.

+14
source

Source: https://habr.com/ru/post/1387440/


All Articles