Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to pass all variables in the current scope to Mako as a context?

I have a method like so:

def index(self):
    title = "test"
    return render("index.html", title=title)

Where render is a function that automatically renders the given template file with the rest of the variables passed in as it's context. In this case, I'm passing title in as a variable in the context. This is a little redundant for me. Is there any way I can automatically pick up all variables defined in the index method and pass them all as part of the context to Mako?

like image 961
Vlad the Impala Avatar asked Jan 29 '26 07:01

Vlad the Impala


1 Answers

Use the technique given below:

def render(template, **vars):
    # In practice this would render a template
    print(vars)

def index():
    title = 'A title'
    subject = 'A subject'
    render("index.html", **locals())

if __name__ == '__main__':
    index()

When you run the above script, it prints

{'subject': 'A subject', 'title': 'A title'}

showing that the vars dictionary could be used as a template context, exactly as if you had made the call like this:

render("index.html", title='A title', subject='A subject')

If you use locals(), it will pass local variables defined in the body of the index() function as well as any parameters passed to index() - such as self for a method.

like image 169
Vinay Sajip Avatar answered Jan 30 '26 20:01

Vinay Sajip