Skip to content

Instantly share code, notes, and snippets.

@clooth
Created August 14, 2012 21:26
Show Gist options
  • Save clooth/3353161 to your computer and use it in GitHub Desktop.
Save clooth/3353161 to your computer and use it in GitHub Desktop.
Grid templatetags
from django import template
register = template.Library()
class GridViewNode(template.Node):
def __init__(self, item_template_name, objects_list):
self.item_template_name = item_template_name
self.objects_list = template.Variable(objects_list)
self.grid_template = template.loader.get_template('common/grid/grid-view.html')
def render(self, context):
try:
objects_list = self.objects_list.resolve(context)
except template.VariableDoesNotExist:
return ''
return self.grid_template.render(template.Context({
'objects_list': objects_list,
'item_template_name': self.item_template_name
}))
@register.tag
def grid_view(parser, token):
try:
tag_name, item_template_name, objects_list = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires two arguments, the item template name and the objects list" % token.split_contents()[0])
return GridViewNode(item_template_name, objects_list)
class GridViewItemNode(template.Node):
def __init__(self, item_template_name, object_instance):
self.item_template_name = template.Variable(item_template_name)
self.object_instance = template.Variable(object_instance)
def render(self, context):
try:
item_template_name = self.item_template_name.resolve(context)
object_instance = self.object_instance.resolve(context)
except template.VariableDoesNotExist:
return ''
item_template = template.loader.get_template(item_template_name[1:-1])
return item_template.render(template.Context({
'object': object_instance
}))
@register.tag
def grid_view_item(parser, token):
try:
tag_name, item_template_name, object_instance = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires two arguments, the item template name and the object instance" % token.split_contents()[0])
return GridViewItemNode(item_template_name, object_instance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment