Skip to content

Instantly share code, notes, and snippets.

@nickhoffman
Created October 18, 2011 15:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nickhoffman/1295692 to your computer and use it in GitHub Desktop.
Save nickhoffman/1295692 to your computer and use it in GitHub Desktop.
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 %>
@tazsingh
Copy link

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
Copy link
Author

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

@nickhoffman
Copy link
Author

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
Copy link

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
Copy link
Author

@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