add variable to all contexts

568 visualizações
Ir para a primeira mensagem não lida

msoulier

não lida,
26/06/2011, 21:38:1026/06/11
para 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

não lida,
26/06/2011, 23:16:1626/06/11
para 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.

A mensagem foi eliminada

Sathit S

não lida,
27/06/2011, 00:42:5427/06/11
para 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

não lida,
27/06/2011, 03:54:3627/06/11
para bott...@googlegroups.com

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

Michael P. Soulier

não lida,
27/06/2011, 10:15:4027/06/11
para 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

Responder a todos
Responder ao autor
Reencaminhar
0 mensagens novas