I am developing a Ruby on Rails 4 application that is using the Turbolinks gem. I have noticed when a link is clicked the layout is still rendered server side but the Turbolinks JavaScript just grabs the body out of this rendered content. My question is on the controller side is it possible to determine if a request is made via Turbolinks or not. Essentially in the event a request is made via Turbolinks I want to set the layout to false as to not execute un-needed code. In my ApplicationController I already have the following code:
我正在开发一个使用Turbolinks gem的Ruby on Rails 4应用程序。我注意到当点击一个链接时,布局仍然呈现在服务器端,但Turbolinks JavaScript只是抓住了这个渲染内容的主体。我的问题是在控制器端是否可以确定是否通过Turbolinks发出请求。基本上,如果通过Turbolinks发出请求,我想将布局设置为false,以便不执行不需要的代码。在我的ApplicationController中,我已经有了以下代码:
# Don't use layout when AJAX request
layout proc { |controller| controller.request.xhr? ? false: "application" }
This code prevents an AJAX request from rendering the header if I make an AJAX request via jQuery, however it doesn't seem to do anything when it comes to Turbolinks.
如果我通过jQuery发出AJAX请求,此代码会阻止AJAX请求呈现标头,但是当涉及到Turbolinks时它似乎没有做任何事情。
1 个解决方案
#1
0
Although this is a bit of a hack, I found that checking the header for "X-XHR-Referer" seems to do the trick.
虽然这有点像黑客,但我发现检查“X-XHR-Referer”的标题似乎可以解决问题。
unless request.headers["X-XHR-Referer"].present?
do_some_stuff
end
It seems that Turbolinks add the header for some redirection handling. This may change in the future though.
看来Turbolinks为一些重定向处理添加了标题。但这可能会在未来发生变化。
#1
0
Although this is a bit of a hack, I found that checking the header for "X-XHR-Referer" seems to do the trick.
虽然这有点像黑客,但我发现检查“X-XHR-Referer”的标题似乎可以解决问题。
unless request.headers["X-XHR-Referer"].present?
do_some_stuff
end
It seems that Turbolinks add the header for some redirection handling. This may change in the future though.
看来Turbolinks为一些重定向处理添加了标题。但这可能会在未来发生变化。