Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pjax is awesome, but causes code within #content_for not to be rendered. Here's a solution.
module ApplicationHelper
def content_for_or_pjax(name, &block)
request.headers['X-PJAX'] ? capture(&block) : content_for(name, &block)
end
end
<%= content_for_or_pjax :javascript do %>
<script type='text/javascript'>
alert('Executing JS!');
</script>
<% end %>
@nickhoffman

This comment has been minimized.

Copy link
Owner Author

@nickhoffman nickhoffman commented Oct 18, 2011

Note that #content_for_or_pjax must be called with <%= rather than <%.

@tazsingh

This comment has been minimized.

Copy link

@tazsingh tazsingh commented Oct 18, 2011

I believe you can get a bit more performance out of that:

def content_for_or_pjax(name)
  request.headers['X-PJAX'] ? yield : content_for(name, &Proc.new)
end

I haven't tested that, but it's a start.

http://mudge.github.com/2011/01/26/passing-blocks-in-ruby-without-block.html

@nickhoffman

This comment has been minimized.

Copy link
Owner Author

@nickhoffman nickhoffman commented Oct 18, 2011

Interesting! That's quite a difference in performance. Thanks for mentioning that.

@nickhoffman

This comment has been minimized.

Copy link
Owner Author

@nickhoffman nickhoffman commented Oct 18, 2011

So it turns out that if you yield within a helper method, you duplicate the entire view. #wtfbbq. Apparently, you need to capture the output from the block that's given to the helper, like this:

capture &block

I've update the code above. I can't believe I just spent 4 hours on that bug...

@dasch

This comment has been minimized.

Copy link

@dasch dasch commented Feb 24, 2012

I use a simple layout for PJAX responses:

<title><%= content_for(:title) %></title>

<script type="text/javascript">
  <%= content_for(:javascript) %>
</script>

<%= yield %>

This allows me to have the views be pretty agnostic about whether or not PJAX is used.

@nickhoffman

This comment has been minimized.

Copy link
Owner Author

@nickhoffman nickhoffman commented Feb 24, 2012

@dasch Simple and great idea. Thanks for sharing that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment