Rails 3.1 template handlers
我有一个 ruby?? gem,poirot,它可以在 Rails 中使用 mustache 模板。我拥有的模板处理程序是从 ActionView::Template::Handler 扩展而来的,但是这在 Rails 3.1 中似乎已被弃用。
我已重构处理程序以符合弃用警告。在这样做时,我现在无法将本地变量或视图上下文传递给模板。我似乎不知道如何在 Rails 3.1 中使用它。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
module Poirot
class Handler attr_reader :template def initialize(template) def self.call(template, *args) def call |
在我上面的处理程序代码中,我得到了模板,它是 ActionView::Template 的一个实例。但我不确定如何获取视图上下文,其中应该包括本地人等
有人能指出我正确的方向吗?
我花了大约 4 个小时研究源代码以找到解决方案,现在看起来很简单:
只需在您想要评估和使用的地方添加 “local_assigns”。
例如:
“#{view_class}.new(self, ‘#{template.source.gsub(/’/,”\\\\\\\\'”)}’, local_assigns).render.html_safe”
这个字符串将在模块上下文中被评估 – ActionView::CompiledTemplates 和 local_assigns 可以在那里访问。
好的,我有一个解决方案,我不确定它是否是最好的,我觉得它有点 hacky!
在我的视图类中,我通过执行以下操作设法访问当地人:
1
|
locals = view_context.send(:view_renderer).send(:_partial_renderer).instance_variable_get(“@locals”) || {}
|
这感觉有点混乱,因为 view_renderer 和 _partial_renderer 都是私有的,并且本地 ivar 没有适当的访问器。
我仍然希望有更好的方法来做到这一点!
来源:https://www.codenong.com/7033530/