【发布时间】:2011-07-14 03:44:27
【问题描述】:
我一直在尝试创建一个基于this Yehuda Katz's blog post 的自定义渲染器。
如果我调用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 源代码,但看起来我对渲染架构的理解不够好。
有人能告诉我问题是什么吗?
【问题讨论】:
-
你需要传递格式变量,所以你需要设置传递它的路由。
-
Rails 3 自动为所有路线传递它。不过,尝试添加它 - 不起作用。 (我做了:
match "/test(.:format)" => "custom_rendering_test#index"和root :to => redirect("/test.my_custom_renderer")) -
让它工作(更新了问题),但不是很好
标签: ruby-on-rails ruby ruby-on-rails-3 renderer