Catalyst Advent - Day 16 - Adding RSS feeds

Adding RSS feeds to your stuff in Catalyst is really simple. I'll show two different aproaches here, but the basic premise is that you forward to the normal view action first to get the objects, then handle the output differently

Using TT templates

This is the aproach we chose in Agave (

    sub rss : Local {
        my ($self,$c) = @_;

Then you need a template. Here's the one from Agave:

As you can see, it's pretty simple.

Using XML::Feed

However, a more robust solution is to use XML::Feed, as we've done in this Advent Calendar. Assuming we have a 'view' action that populates 'entries' with some DBIx::Class/Class::DBI iterator, the code would look something like this:

    sub rss : Local {
        my ($self,$c) = @_;
        $c->forward('view'); # get the entries

        my $feed = XML::Feed->new('RSS');
        $feed->title( $c->config->{name} . ' RSS Feed' );
        $feed->link( $c->req->base ); # link to the site.
        $feed->description('Catalyst advent calendar'); Some description

        # Process the entries
        while( my $entry=$c->stash->{entries}->next ) {
            my $feed_entry = XML::Feed::Entry->new('RSS');
            $feed_entry->link( $c->uri_for($entry->link) );
            $feed_entry->issued( DateTime->from_epoch(epoch   => $entry->created) );
        $c->res->body( $feed->as_xml );

A little more code in the controller, but with this approach you're pretty sure to get something that validates. One little note regarding that tho, for both of the above aproaches, you'll need to set the content type like this:


Final words

Note that you could generalize the second variant easily by replacing 'RSS' with a variable, so you can generate Atom feeds with the same code.

Now, go ahead and make RSS feeds for all your stuff. The world *needs* updates on your goldfish!

-- Marcus Ramberg