场景
例如,下面的代码:
class AwesomeController < ApplicationController
...
def update
respond_to do |format|
format.html
format.turbo_stream
end
end
...
end据我所知,format.turbo_stream的默认行为是在关联的views子目录中呈现一个具有相同操作名称的*.turbo_stream.erb文件。
因此,在本例中,将呈现以下文件:app/views/awesome/update.turbo_stream.erb。
问题
我希望在不同的位置(例如,app/views/somewhere_else/update.turbo_stream.erb)指定一个不同的文件。这个是可能的吗?
自助
在哪里可以找到关于format.turbo_stream
render的turbo_stream选项(例如,render turbo_stream: turbo_stream.update(...) )。我在哪里可以找到这个documentation?发布于 2022-11-27 12:00:38
def update
respond_to do |format|
format.html
format.turbo_stream { render :template } # => renders template.turbo_stream.erb
# format.turbo_stream { render "somewhere/else" }
end
endrender turbo_stream:只设置响应内容-Type: to text/vnd.turbo-stream.html;比如render xml:或者render json:。它本身并不意味着什么,您可以呈现您想要的任何render turbo_stream: "I'm streaming"。在前端,rails很乐意接收到一个内容类型:text/vnd.turbo-Stre.html,但是不会发生任何事情,因为实际的内容看起来不像turbo_stream。为了使某些事情发生,我们需要发送正确的标签:
def update
render turbo_stream: <<~TURBO
<turbo-stream action="append" target="dom_id">
<template>
Content to append to container designated with the dom_id.
</template>
</turbo-stream>
TURBO
end因为这是一种疯狂的方法,所以有一个turbo_stream助手将生成代码。Turbo文档在源代码中:
turbo_stream
turbo_frame_tag
turbo_stream_from
Turbo::Broadcastable
同时,渲染的:turbo_stream选项也没有那么特殊,只要您以正确的内容类型结束,就可以呈现所有类型的内容。
render inline: turbo_stream... # ok
render body: turbo_stream... # fail: Content-Type: text/plain;
render html: turbo_stream... # fail: Content-Type: text/html;
respond_to do |format|
format.turbo_stream do
render inline: turbo_stream... # ok
render body: turbo_stream... # ok
render html: turbo_stream... # fail: Content-Type: text/html;
end
end
# :html was stubborn, but overriding content type makes it work too.
headers["Content-Type"] = Mime[:turbo_stream]respond_to块根据Accept报头决定选择哪种格式。对于涡轮,它是Accept: text/vnd.turbo-stream.html, text/html。因此,您可以使用这些格式进行响应,而turbo将根据响应做出不同的反应。
https://stackoverflow.com/questions/74578154
复制相似问题