Created
October 26, 2011 08:54
-
-
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.
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
# -*- 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 |
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
# -*- coding: utf-8 -*- | |
from *.decorators import template | |
@template('workers/dashboard.html') | |
def dashboard(request): | |
""" | |
Handles serving a dashboard page and such. | |
""" | |
return {'a': 12345} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.