Skip to content

Instantly share code, notes, and snippets.

@codiez
Created November 12, 2009 21:23
Show Gist options
  • Save codiez/233285 to your computer and use it in GitHub Desktop.
Save codiez/233285 to your computer and use it in GitHub Desktop.
Useful Django templatetag that passes a list of choices from your models.py as a context variable to your templates
'''
This Snippet creates a custom template tag for passing a context variable to your template with a list of choices from your models.py i.e
COL_CHOICES =(
(1, 'Not Applicable'),
(2, 'Black'),
)
Usage:
1. Save to template tags dir
2. edit to import the choices you want from your models.py
3. Use in the template like: {% get_options your_choices as variable %}
4. You can then do standard for loops in your templates
'''
from django.template import Library, Node
from django.db.models import get_model
# Change this to import the choices you would like
from myproject.app.models import MY_CHOICES
class OptionsNode(Node):
def __init__(self, options, varname):
self.options = options
self.varname = varname
def render(self, context):
context[self.varname] = self.options
return ''
def get_options(parser, token):
bits = token.contents.split()
if len(bits) !=4:
raise TemplateSyntaxError, "get_options tag takes exactly Four arguments"
if bits[2] != 'as':
raise TemplateSyntaxError, "Third argument to get_options tag must be 'as'"
if bits[1] == 'COL_CHOICES':
choice = COL_CHOICES
return OptionsNode(choice, bits[3])
get_options = register.tag(get_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment