Rails 自定义渲染器
我一直在尝试创建基于 这篇 Yehuda Katz 的博客文章。
如果我调用 render :my_custom_renderer => 它就会起作用“index”,但它不适用于默认的 respond_with
或 format.my_custom_renderer
我创建了一个简单的示例 .
在空白应用程序中,添加以下行:
在 config/mime_types.rb 中:
Mime::Type.register_alias 'text/html', :my_custom_renderer
在 config/my_custom_renderer.rb 中:
require "action_controller/metal/renderers"
ActionController.add_renderer :my_custom_renderer do |template, options|
self.mime_type ||= Mime::HTML
self.response_body = render_to_string(template).sub(/^/,
'\1<h1>Rendering Injection</h1>')
end
在 app/views/custom_renderer_test/index.my_custom_renderer.erb 中:
<h1>A message "Rendering Injection" should appear above</h1>
在 app/controllers/custom_renderer_test_controller.rb 中:
class CustomRenderingTestController < ApplicationController
def index
respond_to do |format|
# does not go through my custom renderer!
format.my_custom_renderer
# although it works if I explicitly do:
# format.my_custom_renderer { render :my_custom_renderer => 'index' }
end
end
end
最后,在 config/routes.rb 中:
root :to => "custom_rendering_test#index"
启动服务器并转到根页面应该显示来自 my_custom_renderer 的消息,但事实并非如此。我已经尝试过逐步调试 Rails 源代码,但看起来我对渲染架构的了解不够深入。
有人可以给我提示一下问题是什么吗?
I've been trying to create a custom renderer based on this Yehuda Katz's blog post.
It works if I call render :my_custom_renderer => "index"
, but it doesn't work with default respond_with
or format.my_custom_renderer
I created a simple example, .
From a blank app, add the following lines:
In config/mime_types.rb:
Mime::Type.register_alias 'text/html', :my_custom_renderer
In config/my_custom_renderer.rb:
require "action_controller/metal/renderers"
ActionController.add_renderer :my_custom_renderer do |template, options|
self.mime_type ||= Mime::HTML
self.response_body = render_to_string(template).sub(/^/,
'\1<h1>Rendering Injection</h1>')
end
In app/views/custom_renderer_test/index.my_custom_renderer.erb:
<h1>A message "Rendering Injection" should appear above</h1>
In app/controllers/custom_renderer_test_controller.rb:
class CustomRenderingTestController < ApplicationController
def index
respond_to do |format|
# does not go through my custom renderer!
format.my_custom_renderer
# although it works if I explicitly do:
# format.my_custom_renderer { render :my_custom_renderer => 'index' }
end
end
end
And, finally, in config/routes.rb:
root :to => "custom_rendering_test#index"
Starting up a server and going to the root page should display the message from my_custom_renderer, but it does not. I've tried debugging Rails source step by step, but looks like I don't understand rendering architecture well-enough.
Can someone please give me a hint on what the problem is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能有用的是使用显式方法创建响应程序(并使用较新的
respond_with
):What might help is to create a responder (and use the newer
respond_with
) with the explicit method: