In many cases, I find out that I can use a single view to render results
from multiple controllers, for example, I use this to render forms::

    {{left_sidebar_enabled=right_sidebar_enabled=False}}
    {{extend 'layout.html'}}
    <h1>{{=title}}</h1>
    {{=form}}

So I stored that view in ``default/form.html``, and I was calling that
this way from the controller::

    def my_form():
# ...
        response.view = 'default/form.'+request.extension
return dict(title=mytitle, form=myform)

But it doesn't look very clear at first look which controllers use which
custom view, etc. so I decided to write a decorator to do that.

I came up with this::

    def use_custom_view(viewname):
        """Decorator to be used to customize the view to be used
        to render a given controller.
        """
        def _use_newcontroller(func):
            def _newcontroller():
                response.view = viewname+'.'+request.extension
                return func()
            return _newcontroller
        return _use_newcontroller

It works quite nicely, and so I replaced the above ``my_form()`` with
this::

    @use_custom_view('default/form')
    def my_form():
        # ...
        return dict(title=mytitle, form=myform)

Then, I decided to move the ``use_custom_view()`` function into a
module, in order to reuse it in many controllers.
So, I created a module named ``helpers`` and placed the decorator
function there.

Now the problem is: how do I access ``request`` and ``response`` from
the module? There are many ways, as passing the two variables as
arguments to constructor, or copying them into the module scope.

I choose the second one, doing this::

    helpers = local_import('helpers')
    helpers.request = request
    helpers.response = response

But I don't like having to do this each time I import that module..
Any suggestions on how to do better?
And, isn't already there something like this in the core?

-- 
Samuele ~redShadow~ Santi
----------------------------------------------------------------
     redshadow[at]hackzine.org - redshadowhack[at]gmail.com

  Blog: http://hackzine.org

  GPG Key signature:
       050D 3E9F 6E0B 44CE C008 D1FC 166C 3C7E EB26 4933
----------------------------------------------------------------
/me recommends:
    Squadra Informatica - http://www.squadrainformatica.com
----------------------------------------------------------------
 - Proud ThinkPad T-Series owner
 - Registered Linux-User: #440008
      * GENTOO User since 1199142000 (2008-01-01)
      * former DEBIAN SID user
----------------------------------------------------------------
      "Software is like sex: it's better when it's free!"
                              -- Linus Torvalds

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to