add variable to all contexts

568 views
Skip to first unread message

msoulier

unread,
Jun 26, 2011, 9:38:10 PM6/26/11
to bottlepy
Hi,

Is there a way to add a variable automatically to every context
without specifying it in each view function?

I suppose I could write a decorator for this but I was wondering if
there's anything built-in.

Mike

Sathit Scraft Programer

unread,
Jun 26, 2011, 11:16:16 PM6/26/11
to bott...@googlegroups.com
My project, I keep all vars in one control dict named "_vars"
and first line of each view, I use 

%locals().update(_vars).

When chaining to other view within tpl, I use like this

%include subpage-ajax _vars=_vars

or like this...

%_include('subpage/'+_vars['subpage'],_stdout, _vars=_vars)


with rebase I use like this

%rebase layout-dynamic _vars=_vars

Replacement of extract all var at first line of view, you can select which vars you requied or optional to use in you view like this:

%_require_vars=['suburl']
%[locals().update({k:_vars[k]}) for k in _require_vars]

%_option_vars=['title','urlsubpage','urloptions','language']
%[locals().update({k:_vars.get(k)}) for k in _option_vars]

different is _require_vars will raise error of missing, but _option_vars not.

sathit

2011/6/27 msoulier <msou...@digitaltorque.ca>

--
You are member of the "bottlepy" group at google groups.
See http://groups.google.de/group/bottlepy for mailing list options.
See http://bottlepy.org/ for news and documentation.

Message has been deleted

Sathit S

unread,
Jun 27, 2011, 12:42:54 AM6/27/11
to bott...@googlegroups.com
I'm not sure, you can try this 

def viewvars(**default) :
    def decorator(func):
        def wrapper() :
            v = {'environ':request.environ}
            v.update(default)
            v.update(func())
            return v
        return wrapper
    return decorator

@get('/')
@view('index')
@viewvars(foot='power by bottle')
def index():
   """Render the front page."""
   global _vars = _vars or dict()
   return dict(title='Home')

sathit

Marcel Hellkamp

unread,
Jun 27, 2011, 3:54:36 AM6/27/11
to bott...@googlegroups.com

It is undocumented, but you can assign values to SimpleTemplate.defaults

Michael P. Soulier

unread,
Jun 27, 2011, 10:15:40 AM6/27/11
to bott...@googlegroups.com
On 27/06/11 Marcel Hellkamp said:

> It is undocumented, but you can assign values to SimpleTemplate.defaults

Ah, we should document it then! :)

This is essentially what Django would call a context processor. They're quite
handy at preventing lots of cutting and pasting.

I did end up using a decorator, but SimpleTemplate.defaults sounds easier. Is
there a way using jinja2 templates?

Thanks,
Mike

Reply all
Reply to author
Forward
0 new messages