Created
November 26, 2011 10:03
-
-
Save senko/1395402 to your computer and use it in GitHub Desktop.
Render a Django template passing all local variables to the RequestContext automatically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import django.shortcuts | |
import inspect | |
def renderlocals(template): | |
""" | |
Renders the template in a RequestContext, passing all local | |
variables to the request context, and returns the resulting | |
HttpResponse. | |
Example usage: | |
def my_view(request): | |
foo = 42 | |
return renderlocals('mytemplate.html') | |
""" | |
locals = inspect.stack()[1][0].f_locals | |
request = locals.get('request') | |
return django.shortcuts.render(request, template, locals) |
Thanks for the info. The (C)Python docs (http://docs.python.org/library/inspect.html) led me to believe only the currentframe() function is CPython-only. I haven't tested it with PyPy or other interpreters - I suppose there's a different but equivalent way of getting the parent stack frame there?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this works on CPython only :)