Skip to content

Instantly share code, notes, and snippets.

@Ogreman
Last active December 27, 2015 11:49
Show Gist options
  • Select an option

  • Save Ogreman/7321101 to your computer and use it in GitHub Desktop.

Select an option

Save Ogreman/7321101 to your computer and use it in GitHub Desktop.
class ContextVariableMixin(object):
"""
Mixin for setting context data using class attributes.
Example:
class MyClass(ContextVariableMixin, View):
prefix = "context_"
context_bar = "foo"
MyClass().get_context_data()["bar"] => "foo"
"""
prefix = "context_"
def get_context_data(self, **kwargs):
context = super(
ContextVariableMixin,
self
).get_context_data(**kwargs)
context.update(
{
var[len(self.prefix):]: getattr(self, var)
for var in dir(self)
if var.startswith(self.prefix)
}
)
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment