Rails 7 + Hotwire/Turbo: Is it possible to specify the location of a turbo_stream.erb template?

637 Views Asked by At

Scenario

Take for example the following code:

class AwesomeController < ApplicationController
  
  ...
  
  def update
    respond_to do |format|
      format.html
      format.turbo_stream
    end
  end
  
  ...
  
end

As I understand it, the default behavior of format.turbo_stream is render a *.turbo_stream.erb file with the same name of the action, in the associated views subdirectory.

So in this case, the following file would be rendered: app/views/awesome/update.turbo_stream.erb.

Question

I want to specify a different file, in a different location (e.g., app/views/somewhere_else/update.turbo_stream.erb). Is this possible?

Self-Help

  • Where can I find the documentation on format.turbo_stream?
  • I'm also particularly interested in reading about the turbo_stream option for render (e.g., render turbo_stream: turbo_stream.update(...). Where can I find this documentation?
1

There are 1 best solutions below

0
On

You can do this:

respond_to do |format|
  format.turbo_stream { render "path-to-file" }
end

Make sure to put the direct path to the file. So for example if I have a file structure like:

/views/posts/custom_turbo_streams/create.turbo_stream.erb

You'll have:

respond_to do |format|
  format.turbo_stream { render "posts/custom_turbo_streams/create" }
end