Navigating Outside a Turbo Frame

Learn to enable a link inside the Turbo Frame to change the parts of the webpage that lie outside it.

Problems in the Previous App

Clicking around the schedule page after adding the edit functionality shows that we moved fast and broke things. Specifically, the links on each concert name that leads to the concert’s page and the “Make Favorite” button appear to be broken. Clicking the concert name does nothing but make the concert display disappear and clicking the “Make Favorite” button updates the concert display but not the “Favorites” section.

Both of these problems have the same cause: the links are now inside a Turbo Frame but try to change parts of the page outside that frame. Turbo Frames, by default, only capture the part of the response that matches the ID of the Turbo Frame that the request came from. In the case of the concert name link, there is no corresponding Turbo Frame, so the existing frame is replaced by nothing. In the case of the “Make Favorite” link, the response is the entire page, which happens to contain a Turbo Frame for the favorited concert, and Turbo updates that frame and that frame alone.

It’s common to need to break out of the Turbo Frame for navigation purposes, so Turbo Frames provides two ways for us to choose from.

Fixes

First, we can set the default target for the entire frame by setting the target= attribute of the HTML <turbo-frame> tag or the target: argument of the turbo_frame_tag helper method. The target is the DOM ID of a different Turbo Frame. By adding the target attribute, we change the behavior of all links within the frame to redraw the target frame rather than the frame from which the link originates. This isn’t what we need for our fixes. The intention is something like a navigation bar where the links would all redraw a content frame rather than redraw the navigation bar itself.

Get hands-on with 1000+ tech skills courses.