Skip to content

Instantly share code, notes, and snippets.

@nickhoffman
Created October 18, 2011 15:20
Show Gist options
  • 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 %>
@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