Search code examples
pyramidmako

How to do fine control of view rendering in Pyramid


The conventional way seems fine:

@view_config(route_name='new', renderer='new.mako')
    return {'tasks': tasks}

But sometimes I may need to have fine control of what I am rendering, ie I may render different views subject to conditions. See this pseudocode:

@view_config(route_name='new')
def new_view(request):
    if request.att == something:
        one_dict = ...
        a = render( "new.mako", one_dict)
    else:
        another_dict = ...
        a = render( "new_special.mako", one_dict)
    return a

How do I render an arbitary template myself with Pyramid's Mako engine and return it as a response?


Solution

  • You can use the render_to_response() renderer here:

    Using the renderer renderer_name (a template or a static renderer), render the value (or set of values) using the result of the renderer's __call__ method (usually a string or Unicode) as the response body.

    For your code that'd be:

    @view_config(route_name='new')
    def new_view(request):
        if request.att == something:
            one_dict = ...
            a = render_to_response("new.mako", one_dict)
        else:
            another_dict = ...
            a = render_to_response("new_special.mako", one_dict)
        return a
    

    or perhaps:

    @view_config(route_name='new')
    def new_view(request):
        if request.att == something:
            renderer = "new.mako"
        else:
            renderer = "new_special.mako"
        return render_to_response(renderer, values)