Skip to content

Instantly share code, notes, and snippets.

@ryanmcgrath
Created October 26, 2011 08:54
Show Gist options
  • Save ryanmcgrath/1315820 to your computer and use it in GitHub Desktop.
Save ryanmcgrath/1315820 to your computer and use it in GitHub Desktop.
An arguably nicer and less verbose way to handle defining view files in Django.
# -*- coding: utf-8 -*-
from django.shortcuts import render
def template(template_path, content_type = 'text/html'):
"""
A Decorator that simplifies a lot of Django view-related cruft, in
regards to rather verbose view serving.
This needs some optimization. This currently caches nothing.
"""
def parse(view_function):
def process(*args, **kwargs):
context = view_function(*args, **kwargs)
return render(args[0], template_path, context, content_type = content_type)
return process
return parse
# -*- coding: utf-8 -*-
from *.decorators import template
@template('workers/dashboard.html')
def dashboard(request):
"""
Handles serving a dashboard page and such.
"""
return {'a': 12345}
@ryanmcgrath
Copy link
Author

I'm a fan of a decorator to define view files, as function names can vary wildly in larger environments. A decorator named @template is pretty apparent that "hey, this is returning a view". It obviously doesn't fit every use case, but nothing does; just another possible option.

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