I'm getting started with Hotwire and Turbo in Rails 6 and have an issue with Turbo not replacing my turbo-frame. I'm receiving the following error message: Response has no matching <turbo-frame id="experiments"> element
.
I have the following being rendered on the page from a controller action:
<!-- index.html.erb -->
<turbo-frame id="experiments" src="/labs/experiments">
<p>This message will be replaced by the response from /labs/experiments.</p>
</turbo-frame>
This correctly sends the request to /labs/experiments
, and when I check my network requests the following is returned from my controller:
<h2>Experiment 1</h2>
<h2>Experiment 2</h2>
However, the response is not rendered inside my turbo-frame and instead I receive a console log warning: Response has no matching <turbo-frame id="experiments"> element
.
Any help is appreciated :)
Okay I figured out what was happening.
The response to the turbo-frames request must contain the same id
as the turbo-frame that sent it. Since the turbo-frame in index.html.erb contains an id of 'experiments':
<!-- response from /labs/experiments wrapped in turbo-frame with id -->
<turbo-frame id="experiments">
<h2>Experiment 1</h2>
<h2>Experiment 2</h2>
</turbo-frame>
This entirely fixed the error I was receiving, and turbo started populating the turbo-frame with the results from the server.
erb
Since I haven't been able to find too many full examples yet, here is my simple example of using turbo-frames (which are awesome!). Note that the routes, controller methods (etc) are intentionally over simplified, but helped greatly in my understanding:
get 'examples' => 'examples#index'
get 'examples/experiments' => 'examples#experiments'
class ExamplesController < ApplicationController
# renders some simple html, including a turbo-frame
def index; end
# renders the content of the turbo-frame
def experiments
@experiments = [
{ name: 'React Keyboarding Environment', url: '/keyboarding' },
{ name: 'Accessible Keyboarding', url: '/accessible' }
]
render partial: 'experiments'
end
end
app/views/examples/index.html.erb
<h1>Examples#index</h1>
<turbo-frame id="experiments" src="/examples/experiments">
<p>This message will be replaced by the response from /experiments.</p>
</turbo-frame>
app/views/examples/_experiments.html.erb
<%= turbo_frame_tag :experiments do %>
<% @experiments.each do |experiment| %>
<h2><%= experiment[:name] %></h2>
<% end %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With