ff10ecd13409 — Peter Sanchez 13 years ago
Added template tags.. Still needs testing
M twittersync/models.py +1 -1
@@ 54,7 54,7 @@ class TwitterStatus(models.Model):
 
     class Meta:
         get_latest_by = 'created_date'
-        ordering = ('id',)
+        ordering = ('-date',)
 
     def __unicode__(self):
         return u'%i' % self.id

          
A => twittersync/templatetags/__init__.py +0 -0

A => twittersync/templatetags/twittersync_tags.py +67 -0
@@ 0,0 1,67 @@ 
+from django.conf import settings
+from django import template
+from twittersync.models import TwitterAccount, TwitterStatus
+
+register = template.Library()
+
+
+class LatestTweets(template.Node):
+    def __init__(self, account, limit, varname):
+        self.account = account
+        self.limit = limit
+        self.varname = varname
+
+    def render(self, context):
+        def resolve_or_not(var, context):
+            if callable(getattr(var, 'resolve', None)):
+                return var.resolve(context)
+            return var
+
+        account = resolve_or_not(self.account, context)
+        limit = resolve_or_not(self.limit, context)
+        varname = resolve_or_not(self.varname, context)
+
+        if not isinstance(account, TwitterAccount):
+            try:
+                account = TwitterAccount.objects.get(screen_name=account)
+            except TwitterAccount.DoesNotExist:
+                raise
+
+        context[varname] = account.tweets.all()[:limit]
+
+
+@register.tag
+def get_latest_tweets(parser, token):
+    ''' Returns the latest tweets stored in the db.
+
+        Run like so:
+
+        {% get_latest_tweets twitter_account_instance 5 as tweets %}
+
+        Will return the last 5 tweets and store in the 
+        template context as "tweets"..
+
+        You can also exclude the number requested and 
+        the tag will return the value set in 
+        settings.TWITTERSYNC_LATEST_TWEETS. If that 
+        isn't set, we fall back to 5
+    '''
+    if len(bits) < 4:
+        raise template.TemplateSyntaxError(
+            '"%s" tag takes at least 3 arguments' % bits[0]
+        )
+
+    limit = None
+    try:
+        _tag, account, limit, _as, varname = bits
+    except ValueError:
+        _tag, account, _as, varname = bits
+
+    if limit is None:
+        limit = getattr(settings, 'TWITTERSYNC_LATEST_TWEETS', 5)
+
+    return LatestTweets(
+        parser.compile_filter(account),
+        parser.compile_filter(limit),
+        parser.compile_filter(varname),
+    )