Render partial from an atom builder view

Published on and tagged with ruby on rails  view

Thanks to the built-in AtomFeedHelper it is quite easy to generate an atom feed with Rails.

Here an example from the API:

# app/views/posts/index.atom.builder
atom_feed do |feed|
  feed.title("My great blog!")
  feed.updated(@posts.first.created_at)

  @posts.each do |post|
    feed.entry(post) do |entry|
      entry.title(post.title)
      entry.content(post.body, :type => 'html')

      entry.author do |author|
        author.name("DHH")
      end
    end
  end
end

The code should be self-explanatory (if not, please leave a comment).

Recently, I had two such views which were almost identical, the only difference was the feed title. And that’s of course not really DRY.

One possible approach to fix this “issue” is to set an instance variable with the feed title in the controller and render the same view in both cases. As I don’t like to set view titles (resp. feed titles in this case) in the controller, I decided to use a partial.

And so I put the code from above into a partial (plus changing the instance variable “@posts” to a local variable “posts” and introducing a new local variable “feed_title”), and tried to use this partial (app/views/shared/_feed.atom.builder) in the following way:

# app/views/posts/index.atom.builder
render :partial => 'shared/feed', :locals => {:feed_title => "My Posts", :posts => @posts}

Well, it didn’t work. No output was generated.

After experimenting a bit I found the following solution by moving the outer-most block definition from the partial to the views:

# app/views/posts/index.atom.builder
atom_feed do |feed|
  render :partial => 'shared/feed', :locals => {:feed => feed, :feed_title => "My Posts", :posts => @posts}
end

I don’t know whether this is the best solution (probably not), but it is definitely better than what I had previously ;-)

3 comments baked

  • Render partial from an atom builder view [ cakebaker ]

    […] Render partial from an atom builder view November 27th 2009 2:02pm Thanks to the builtin AtomFeedHelper it is quite easy to generate an atom feed with Rails Here an example from the API appviewspostsindexatombuilder atomfeed do 124feed124 feedtitleMy great blog feedupdatedpostsfirstcreatedat postseach do 124post124 feedentrypost do 124entry124 entrytitleposttitle entrycontentpostbody type 62 From: cakebaker.42dh.com […]

  • Boris Barroso

    Hi there I haven’t tested but maybe you could add the

    atom_feed do |feed|
    

    in the partial, I haven’t teted but I think it could be nice to do this directly in the partial instead of adding it in the controller

  • cakebaker

    @Boris: Thanks for your comment!

    Well, having

    atom_feed do |feed|
    

    in the partial was my first thought, but for some reason I never got any output, hence I put it into the views which render the respective partial.

© daniel hofstetter. Licensed under a Creative Commons License