Turbo-stream inside turbo-frame response. Is this a legit pattern?

I saw somewhere that someone was putting a tubro_stream inside a turbo_frame response for a standard http GET request. I don’t think it was a form submission, just a GET.

Is this valid? The docs make it sound like turbo-stream are only for broadcasting and form submissions, not standard turbo_frame requests.

1 Like

It’s legit because even the server-broadcasted format.turbo_stream use the javascript magic that adding a turbo_stream inside a turbo_frame does.

Both end up having a <turbo-stream><template></template></turbo-stream> element being added to the page, getting picked up by the JavaScript magic (a MutationObserver) that then either appends or replaces or updates elements on the page with the same id or classes.

So it’s legit, and sometimes it allows you to package both the updated HTML inside the turbo_frame itself and updating a different part of the page (e.g. adding a flash message somewhere else on the page) in the same response.

1 Like

Interesting. So that makes me wonder why we respond to form submission differently (in a Rails application) then other requests.

For example, for a form submission we do

render turbo_stream: render turbo_stream: turbo_stream.replace(...)

But we simply render a template for turbo_frame requests.

My understanding is that these methods are not interchangeable, but your answer makes me wonder why not, given they are essentially the same in the end result.

How would one go about rendering a stream inside a frame? I ask this in view of considering how HTML partials are sliced up and saved.

I’m so glad that I stumbled upon this post! I had no idea that you could include inline <turbo-stream> elements. I don’t believe this is mentioned anywhere in the documentation (unless my n00b brain just didn’t understand what I was reading). Anyway, huge thanks!

@hotphp this might be of interest to you - I put together a small demo for myself, and I made sure to include an async <turbo-frame> response that has an embedded <turbo-stream> transformation that gets applied to the parent page.

Hi Ben,

I understand the structure of the required response.

My concern is, most backends will render the full HTML of the page in question, so it would appear the backend needs to parse this HTML and identify where to insert the stream.

How do we do this robustly without parsing or breaking the HTML

Yeah, good question. I’m still just trying to wrap my head around the mechanics of the Hotwire framework. I don’t think I even have a good sense yet for how the back-end fits together properly. My initial feelings here are that this (Turbo Stream in an HTML response) mostly makes in a Turbo Frame response. But, it’s all just theory in my head so far.