zhisme
zhisme

Reputation: 2800

turbo_frame_tag request with other formats than HTML

Given the following

<%= turbo_frame_tag dom_id(@item, "loader_helper"), src: home_index_path(@item) %>

This code will trigger with page load other request to specified controller

Started GET "/home/1" for ::1 at 2023-01-23 16:10:39 +0300
Processing by HomeController#index as HTML

The problem is that I want to render not HTML, but rather turbo_stream format with some page modifications and don't rely on some JS solution.

So I would expect the following pseudocode to work

<%= turbo_frame_tag dom_id(@item, "loader_helper"), src: home_index_path(@item), format: :turbo_stream %>

to load action like so

Started GET "/home/1" for ::1 at 2023-01-23 16:10:39 +0300
Processing by HomeController#index as TURBO_STREAM

and then in controller I can handle it with specific formats

..
def index
  respond_to do |format|
    format.html
    format.turbo_stream
  end
end

Are there any workarounds? Or this is intended by design, so we won't be able to trigger turbo_stream on page load (you can do it with js easily), and manipulate with some HTML.

Upvotes: 3

Views: 1868

Answers (2)

anka
anka

Reputation: 3857

Thanks for the question and the answer. I got it working too for my use case with the following code:

The view file, containing the turbo frame and requesting the index action of the Calculators controller:

<%= turbo_frame_tag :calculator, src: calculators_path(format: :turbo_stream) do %>
   <!-- some initial HTML content -->
<% end %>

The Calculators controller and its index action:

def index
  respond_to do |format|
    format.turbo_stream
  end
end

The turbo stream file index.turbo_stream.erb rendering the partial _new.html.erb:

<%= turbo_stream.update "calculator", partial: "calculators/new" %>

Upvotes: 1

Saiqul Haq
Saiqul Haq

Reputation: 2397

Based on the doc https://turbo.hotwired.dev/handbook/streams it injects text/vnd.turbo-stream.html for POST, PUT, PATCH, or DELETE HTTP method. If you want to use it for the GET method, you must add the data-turbo-stream attribute. So for your case, you can try the following code:

<%= turbo_frame_tag dom_id(@item, "loader_helper"), src: home_index_path(@item, format: :turbo_stream) %>

Reference: https://github.com/hotwired/turbo-site/pull/40#discussion_r570471371

Upvotes: 4

Related Questions