Geo
Geo

Reputation: 96867

How can I get the content of the block to appear in the view?

I have some code like this:

<% cache "footer_links" do %>
  <%= cms_snippet_content('footer_links') %>
<% end %>

And I thought of writing a helper method, like this one:

def cached_snippet_content(snip_id)
  cache(snip_id) do
    cms_snippet_content(snip_id)
  end
end

However, I don't get any output in my view, even though, my erb code looks like this:

<%= cached_snippet_content "footer_links" %>

What am I doing wrong?

Upvotes: 1

Views: 278

Answers (3)

tokland
tokland

Reputation: 67890

May the source be with you, Luke:

# actionpack-3.2.0/lib/action_view/helpers/cache_helper.rb
def cache(name = {}, options = nil, &block)
  if controller.perform_caching
    safe_concat(fragment_for(name, options, &block))
  else
    yield
  end

  nil
end

This shows that cache is implemented to be called from ERB views, not from helpers. An alternative implementation:

def cache(name = {}, options = nil, &block)
  if controller.perform_caching
    fragment_for(name, options, &block)
  else
    capture(&block)
  end
end

And now use it with the new Rails ERB style (<%= ... > even in blocks if they output something):

<%= cache "key" do %>
  <%= content_tag(:p, "hello") %>
<% end %>

I'd test this carefully, there may be hidden corners, I guess there'll be a reason why cache has not been adapted to the Rails 3 block style.

Upvotes: 1

Matzi
Matzi

Reputation: 13925

Try this:

def cached_snippet_content(snip_id)
  a = ""
  cache(snip_id) do
    a += cms_snippet_content(snip_id).to_s
  end
  a
end

Upvotes: 0

Charles Caldwell
Charles Caldwell

Reputation: 17169

It looks like the do block in your helper method isn't returning anything and hence the entire helper method isn't returning anything and henceforth there's nothing for the view to display.

Maybe try this:

def cached_snippet_content(snip_id)
  cache(snip_id) do
    result = cms_snippet_content(snip_id)
  end
  result
end

Upvotes: 0

Related Questions