Created
June 5, 2010 02:21
-
-
Save osantana/426228 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
from inspect import getouterframes, currentframe | |
from copy import copy | |
from django.shortcuts import render_to_response | |
#def render_to_response(*args, **kw): | |
# print args, kw | |
class Templater(object): | |
def __init__(self, **kwargs): | |
self.args = kwargs | |
self._prev = set() | |
def __enter__(self): | |
self._prev = set(getouterframes(currentframe())[1][0].f_locals.keys()) | |
return self | |
def __exit__(self, type_, value, traceback): | |
current = getouterframes(currentframe())[1][0].f_locals | |
newvars = set(current.keys()) - self._prev | |
for name in newvars: | |
if current[name] is not self: | |
self.args[name] = current[name] | |
def render_to_response(self, template, context_instance=None, mimetype=None): | |
return render_to_response(template, self.args, context_instance, mimetype) | |
def view(request, arg): | |
a = 1 | |
with Templater(arg=arg) as t: | |
b = 2 | |
# send {'arg': arg, 'b': 2} to template.html | |
return t.render_to_response("template.html", context_instance="ctx", mimetype="mime") |
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
class Templater(object): | |
def __init__(self, **kwargs): | |
self._args = kwargs | |
def __setattr__(self, name, value): | |
if name == "_args": | |
return super(Templater, self).__setattr__(name, value) | |
self._args[name] = value | |
def __getattr__(self, name): | |
try: | |
return self._args[name] | |
except KeyError, ex: | |
raise AttributeError("%s instance has no attribute %r" % (self.__class__.__name__, name)) | |
def render_to_response(self, filename, context_instance=None, mimetype=None): | |
return render_to_response(filename, self._args, context_instance, mimetype) | |
def view(request, arg): | |
t = Templater(arg=arg) | |
t.object = get_object_or_404(User, username=request.user.username) | |
t.arg2 = "foobar" | |
# Send {'arg': arg, 'object': <User..>, 'arg2': 'foobar'} to template.html | |
return l.render_to_response("template.html", context_instance=RequestContext(request)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sim... seria... :D
Deixa eu corrigir :D