我有一颗 ruby ,poirot ,它允许在 Rails 中使用 mustache 模板。我拥有的模板处理程序是从 ActionView::Template::Handler 扩展而来的,但是这在 Rails 3.1 中似乎已被弃用。
我已重构处理程序以符合弃用警告。在这样做时,我现在无法将局部变量或 View 上下文传递给模板。我似乎无法找到如何让它与 Rails 3.1 一起工作。
module Poirot
class Handler
attr_reader :template
def initialize(template)
@template = template
end
def self.call(template, *args)
self.new(template).call
end
def call
view_path = "#{template.virtual_path}_view"
abs_view_path = Rails.root.join('app/views', view_path)
view_class = begin
view_path.classify.constantize
rescue NameError => e
Poirot::View
end
"#{view_class}.new(self, '#{template.source.gsub(/'/, "\\\\'")}').render.html_safe"
end
end
end
在我上面的处理程序代码中,我传递了模板,它是 ActionView::Template 的一个实例。但我不确定如何获取 View 上下文,其中应包括本地人等
有人能指出我正确的方向吗?
最佳答案
好吧,我有一个解决方案,我不确定它是不是最好的,我觉得它有点老套!
在我的 View 类中,我通过执行以下操作设法访问了本地人:
locals = view_context.send(:view_renderer).send(:_partial_renderer).instance_variable_get("@locals") || {}
这感觉有点困惑,因为 view_renderer 和 _partial_renderer 都是私有(private)的,并且没有适当的本地 ivar 访问器。
我仍然希望有更好的方法来做到这一点!
关于ruby-on-rails - Rails 3.1 模板处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033530/