Login

Parsed RSS into template var

Author:
bram
Posted:
July 4, 2008
Language:
Python
Version:
.96
Tags:
template tag templatetag cache rss parse
Score:
-1 (after 3 ratings)

loads a parsed RSS feed (with feedparser) into a variable of choice. Caching by the "cache" template tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from django import template
import feedparser

register = template.Library()

class RssParserNode(template.Node):
    def __init__(self, var_name, url=None, url_var_name=None):
        self.url = url
        self.url_var_name = url_var_name
        self.var_name = var_name

    def render(self, context):
        if self.url:
            context[self.var_name] = feedparser.parse(self.url)
        else:
            try:
                context[self.var_name] = feedparser.parse(context[self.url_var_name])
            except KeyError:
                raise template.TemplateSyntaxError, "the variable \"%s\" can't be found in the context" % self.url_var_name
        return ''

import re

@register.tag(name="get_rss")
def get_rss(parser, token):
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    url, var_name = m.groups()
    
    if url[0] == url[-1] and url[0] in ('"', "'"):
        return RssParserNode(var_name, url=url[1:-1])
    else:
        return RssParserNode(var_name, url_var_name=url)
    
"""
example usage:

{% load cache %}
{% load rss %}

{% cache 500 rss_display %}
	{% get_rss "http://www.freesound.org/blog/?feed=rss2" as rss %}
	{% for entry in rss.entries %}
		<h1>{{entry.title}}</h1>
		<p>
			{{entry.summary|safe}}
		</p>
		<p>
			<a href="{{entry.link}}">read more...</a>
		</p>
	{% endfor %}
{% endcache %}
"""

More like this

  1. Feed Reader Inclusion Tag with Caching by baumer1122 7 years, 8 months ago
  2. twitter_status by zodman 6 years, 8 months ago
  3. Feed Reader Inclusion Tag by baumer1122 7 years, 9 months ago
  4. extend tag with cache by fredd4 7 years, 2 months ago
  5. Deli.cio.us rss template tag by aaloy 6 years ago

Comments

ericflo (on July 4, 2008):

django-feedutil and django-template-utils both have almost this exact same feature already. But I have to admit, it's kind of nice as a self-contained snippet.

#

bram (on July 31, 2008):

I've edited it slightly, now it can also take a template-variable. For example:

{% get_rss rss_url as rss %}

#

Please login first before commenting.