Commits

Zakhar Zibarov committed 0967c58

добавлен {% inject_fave_counts_to [objects] of type [fave-type-slug] as [attribute_name] %}

  • Participants
  • Parent commits 36ec2d1

Comments (0)

Files changed (1)

File faves/templatetags/faves.py

     validate_template_tag_params(bits, 7, {1:'on', 3:'of', 4:'type', 6:'as'})
 
     return GetFavoriteCountNode(bits[2], bits[5], bits[7])
+
+
+class InjectFaveCountsToNode(template.Node):
+    def __init__(self, object_list, fave_type_slug, varname):
+        self.object_list, self.fave_type_slug, self.varname = object_list, fave_type_slug, varname
+
+    def render(self, context):
+        obj_list = resolve_variable(self.object_list, context)
+
+        ''' allow single object to be passed by putting it into list '''
+        try:
+            iter(obj_list)
+        except TypeError:
+            obj_list = [obj_list]
+
+        content_type = ContentType.objects.get_for_model(obj_list[0])
+        obj_ids = [obj.id for obj in obj_list]
+
+        result = dict(Fave.objects.active() \
+                    .filter(type__slug=self.fave_type_slug,
+                            content_type=content_type,
+                            object_id__in=obj_ids) \
+                    .values_list('object_id').annotate(c=models.Count('id')))
+
+        for obj in obj_list:
+            setattr(obj, self.varname, result.get(obj.id, 0))
+
+        return ''
+
+
+@register.tag
+def inject_fave_counts_to(parser, token):
+    """
+    Adds attribute with Fave instance for each favorited object in `objects` list (iterable with django models)
+
+    Syntax::
+
+        {% inject_fave_counts_to [objects] of type [fave-type-slug] as [attribute_name] %}
+
+    Example::
+
+        {% inject_fave_counts_to page.object_list of type favorites as fave_count %}
+
+        {% for object in page.object_list %}
+            {{ object }} +{{ object.fave_count }}
+        {% endfor %}
+
+    """
+    bits = token.contents.split()
+    validate_template_tag_params(bits, 6, {2:'of', 3:'type', 5:'as'})
+
+    return InjectFaveCountsToNode(bits[1], bits[4], bits[6])
+
+