Commits

Anonymous committed 51d9fac

added render_object filter, to render generic objects with auto-named templates

  • Participants
  • Parent commits a47ea38

Comments (0)

Files changed (1)

File template_utils/templatetags/generic_filters.py

+from django import template
+from django.template.loader import get_template
+from django.conf import settings
+
+RENDER_OBJECT_SUFFIX = getattr(
+    settings, 'TEMPLATE_UTILS_RENDER_OBJECT_SUFFIX', 'filter')
+
+def do_render_object(obj, variant=''):
+    """
+    Stores ``obj`` in a context variable called ``object`` and
+    passes it to a template named as
+
+        [app_label]/[model_name]_[variant]_[TEMPLATE_UTILS_RENDER_OBJECT_SUFFIX].html
+    
+    if ``variant`` is empty then it will be
+
+        [app_label]/[model_name]_[TEMPLATE_UTILS_RENDER_OBJECT_SUFFIX].html
+    
+    where
+
+        * ``app_label`` is ``obj._meta.app_label`` (e.g., ``foo_app``)
+        * ``model_name`` is ``obj._meta.model_name.lower()`` (e.g., ``person``)
+        * ``TEMPLATE_UTILS_RENDER_OBJECT_SUFFIX`` is a setting
+          variable (default to ``filter``)
+        * ``variant`` is a user-supplied string that specifies a template variant
+
+    Syntax::
+    
+        {{ [obj]|render_object:"[variant]" }}
+    
+    Example::
+    
+        {{ person|render_object:"wide" }}
+        
+    """
+    o = obj._meta
+    name = o.object_name.lower()
+    app = o.app_label
+
+    if len(variant) > 0:
+        variant = '_%s' % variant
+    else:
+        variant = ''
+
+    t = get_template(
+        '%s/%s%s_%s.html' % (app, name, variant, RENDER_OBJECT_SUFFIX))
+    
+    return t.render(template.Context({'object': obj}))
+
+register = template.Library()
+register.filter('render_object', do_render_object)