【问题标题】:Rails 3.1 template handlersRails 3.1 模板处理程序
【发布时间】:2011-10-25 09:36:51
【问题描述】:

我有一个 ruby​​ gem,poirot,它可以在 Rails 中使用 mustache 模板。我拥有的模板处理程序是从 ActionView::Template::Handler 扩展而来的,但是这似乎在 Rails 3.1 中已被弃用。

我已重构处理程序以符合弃用警告。在这样做时,我现在无法将本地变量或视图上下文传递给模板。我似乎不知道如何在 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 的一个实例。但我不确定如何获取视图上下文,其中应该包括本地人等

有人能指出正确的方向吗?

【问题讨论】:

    标签: ruby-on-rails ruby actionview mustache


    【解决方案1】:

    好的,我有一个解决方案,我不确定它是不是最好的,我觉得有点 hacky!

    在我的视图类中,我通过执行以下操作设法访问当地人:

    locals = view_context.send(:view_renderer).send(:_partial_renderer).instance_variable_get("@locals") || {}
    

    这感觉有点混乱,因为 view_renderer 和 _partial_renderer 都是私有的,并且本地 ivar 没有适当的访问器。

    我仍然希望有更好的方法来做到这一点!

    【讨论】:

      【解决方案2】:

      我花了大约 4 个小时研究源代码以找到解决方案,现在看起来很简单:

      只需在您想要评估和使用的地方添加“local_assigns”。

      例如:

      "#{view_class}.new(self, '#{template.source.gsub(/'/, "\\\\'")}', local_assigns).render.html_safe"

      此字符串将在模块上下文中进行评估 - ActionView::CompiledTemplates 和 local_assigns 将可以在那里访问。

      【讨论】:

        猜你喜欢
        • 2011-10-26
        • 1970-01-01
        • 2011-10-14
        • 1970-01-01
        • 2012-10-12
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        • 2011-11-25
        相关资源
        最近更新 更多