在 response_to 中呈现不同的 Javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3539090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rendering a different Javascript file in respond_to
提问by Alessandro DS
I am stuck in an (apparently) simple problem. In my event_controller I have the i_like_it action:
我陷入了一个(显然)简单的问题。在我的 event_controller 我有 i_like_it 动作:
def i_like_it
@event = Event.find(params[:id])
... # logic
respond_to do |format|
format.js
end
end
In my case "i_like_it" is called with :method => PUT (it is an Ajax call, "i_like_it.js.erb" will be returned as a script and it wil be executed on the browser.)
在我的例子中,“i_like_it”是用 :method => PUT 调用的(这是一个 Ajax 调用,“i_like_it.js.erb”将作为脚本返回,它将在浏览器上执行。)
I would like render a Javascript file with a different name(not i_like_it.js.erb) , but I haven't found any option in the Rails API docs.
我想渲染一个具有不同名称的 Javascript 文件(不是 i_like_it.js.erb),但我在 Rails API 文档中没有找到任何选项。
respond_to do |format|
format.js { render ??? }
end
Rails can render vanilla JavaScript with :js option, but I don't want use Javascript in the controller.
Rails 可以使用 :js 选项呈现 vanilla JavaScript,但我不想在控制器中使用 Javascript。
Do you have any suggestion ?
你有什么建议吗?
Thank you, Alessandro DS
谢谢你,亚历山德罗 DS
采纳答案by Nikita Rybak
Try render :template => 'your_file_here'instead of
尝试render :template => 'your_file_here'代替
respond_to do |format|
format.js
end
Documentation for renderdescribes a couple of other options too.
的文档也render描述了其他几个选项。
回答by cpm
If you do:
如果你这样做:
respond_to do |format|
format.js { render :action => "different_action" }
end
it will load RAILS_ROOT/app/views/your-controller/different_action.js.erb instead.
它将改为加载 RAILS_ROOT/app/views/ your-controller/different_action.js.erb。
The format.js block just ensures that if it's a .js request, you have the proper headers set by default and it looks for .js.erb or .js instead of .html.erb by default.
format.js 块只是确保如果它是 .js 请求,默认情况下您设置了正确的标头,并且默认情况下它会查找 .js.erb 或 .js 而不是 .html.erb。
You can also use render :file to render any arbitrary file on the file system that happens to have JS in it, or you could use any of render's other usual options. There are a few of them.
您还可以使用 render :file 来渲染文件系统上碰巧包含 JS 的任意文件,或者您可以使用任何渲染的其他常用选项。有几个。

