Created
October 18, 2011 15:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ApplicationHelper | |
def content_for_or_pjax(name, &block) | |
request.headers['X-PJAX'] ? capture(&block) : content_for(name, &block) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= content_for_or_pjax :javascript do %> | |
<script type='text/javascript'> | |
alert('Executing JS!'); | |
</script> | |
<% end %> |
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
Interesting! That's quite a difference in performance. Thanks for mentioning that.
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...
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.
@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
Note that
#content_for_or_pjax
must be called with<%=
rather than<%
.