Search code examples
pythontemplatestemplate-enginebottle

how to pass own dictionary to sub-template


using bottlepy with the simple template engine i wonder how i could pass the entire dictionary that was passed to the template on to it's sub-templates.

e.g. in my main.py i have:

@bottle.route('/')
@bottle.view('main')
def index():
    """main page"""
    return {"name": "main", "foo": 12, "flag": True}

and i want to pass on all the values in the dictionary from my main.tpl to a sub.tpl

$ cat sub.tpl
<h1>Hello, {{name}}</h1>

$ cat main.tpl
% include('subtemplate', name=name, foo=foo, flag=flag)

enumerating each key (as in the above example), is of course not very scalable nor flexible.

so: is there a way to pass on the entire environment?

something like

$ cat main.tpl
% include('subtemplate', *env)

Solution

  • Just a thought, off the top of me head. (I.e., untested.)

    @bottle.route('/')
    @bottle.view('main')
    def index():
        """main page"""
        env = {"name": "main", "foo": 12, "flag": True}  # same vars as before
        env["env"] = env  # add a reference to the entire dict, for passing deeper into subtemplates
        return env
    

    And then:

    % include('subtemplate', env=env)
    

    EDIT

    Thanks to @Kwartz for suggesting the following improvement.

    A cleaner method would be, simply:

    % include('subtemplate', **env)
    

    Have not tried it, but if **locals() works (h/t to @Lukas Graf for trying it and confirming), then it's reasonable to expect **env to work as well.