I am working on a small library/gem (tentatively called turbo_router) that makes your Rails app dynamically respond to requests with the proper layout, whether the request is a turbo_frame request or a navigation from an external source.
This allows me to use the exact same templates for either situation, since it simply wraps the show.erb
template in either the application layout (for external requests) or a layout that wraps it in a turbo_frame to replace my main page content (for turbo_frame requests).
All this is working really well and I even have helpers such as turbo_router_link_to
and turbo_router_route_to
(first one makes a link that just replaces your main content, while the second one advances history as well) and I boiled down form logic to a single line in many cases that handles both turbo_frame requests as well as normal requests.
I am trying to extend this functionality to form submissions too, and I got a working solution, but it is kinda hacky because I don’t know how to render turbo_streams with a layout. For whatever reason, the proc I use to set the layout for each request just isn’t getting called.
The following code is from the module I include in my controllers.
module TurboRouter
extend ActiveSupport::Concern
included do
layout -> do
turbo_router_layout? ? "layouts/turbo_router_content" : self.class.page_layout
end
Anyway I think/hope this gem will be useful to the community as it really cuts down on a lot of boilerplate code such as certain data attribute in our views as well as the cumbersome controller logic. For example, this is my show action:
def show
@post = Post.find(params[:id])
turbo_router
end
and that is able to respond to external navigations directly to the post (.i.e …/posts/2) as well as turbo_frame navigations, with only a single view template.
Anyway, working on getting this published as a gem. Would love to find a cleaner way to handle form submission stuff using layouts + turbo_streams. Right now I am rendering a special layout with a dynamic render statement inside of it instead of a yield in order to render turbo_streams with the correct turbo_frame wrapper, using the same template as the show action, for example.
Any help is appreciated!