ohmu
ohmu

Reputation: 19752

Access view configuration from renderer

Is there a way to access the view configuration from a renderer? By view configuration I mean the arguments passed to the view_config() decorator. My goal is to add some settings to the view configuration which a renderer can then use.

I have a custom renderer:

class MyRenderer(object):
    def __init__(self, info):
        pass

    def __call__(self, value, system):
        # Get view options.
        my_renderer_opts = ...

        # Render using options.
        ...

which is registered as:

config.add_renderer('my_renderer', MyRenderer)

Then in my view I have:

class Page(object):
    def __init__(self, request):
        self.request = request

    @pyramid.view.view_config(
        route_name='root',
        renderer='my_renderer',
        my_renderer_opts={...}
    )
    def view(self):
        pass

Is there a way to access my_renderer_opts passed to view_config() from MyRenderer.__call__()?

Upvotes: 1

Views: 168

Answers (1)

slav0nic
slav0nic

Reputation: 3795

if you still want implement it as described, maybe deriver will be helpfull:

from wsgiref.simple_server import make_server
from pyramid.view import view_config
from pyramid.config import Configurator


@view_config(route_name="hello", renderer="myrend", renderer_options={"a": 1})
def hello_world(request):
    return "Hello World!"


def rendereropt_deriver(view, info):
    options = info.options.get("renderer_options", {})

    def wrapped(context, request):
        setattr(request, "_renderer_options", options)
        return view(context, request)
    return wrapped


rendereropt_deriver.options = ("renderer_options",)


class MyRendererFactory:
    def __init__(self, info):
        self.info = info

    def __call__(self, value, system):
        options = getattr(system["request"], "_renderer_options", {})
        print("`renderer_options` is {}".format(options))
        return value


if __name__ == "__main__":
    with Configurator() as config:
        config.add_route("hello", "/")
        config.add_view_deriver(rendereropt_deriver)
        config.add_renderer("myrend", MyRendererFactory)
        config.scan(".")
        app = config.make_wsgi_app()
    server = make_server("0.0.0.0", 8000, app)
    server.serve_forever()

Upvotes: 2

Related Questions