Skip to content

Instantly share code, notes, and snippets.

@osantana
Created June 5, 2010 02:21
Show Gist options
  • Save osantana/426228 to your computer and use it in GitHub Desktop.
Save osantana/426228 to your computer and use it in GitHub Desktop.
#!/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")
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))
@osantana
Copy link
Author

osantana commented Jun 5, 2010

Warning: No tests.

@ehabkost
Copy link

ehabkost commented Jun 5, 2010

Qual deveria ser o comportamento esperado se alguém fizer o seguinte?

t = Templater(arg=arg)
a = 1
with t:
    b = 2

Não seria um comportamento mais óbvio salvar self.prev no _enter()?

@osantana
Copy link
Author

osantana commented Jun 7, 2010

Sim... seria... :D

Deixa eu corrigir :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment