【问题标题】:render_to_string in lib class not workinglib类中的render_to_string不起作用
【发布时间】:2011-02-10 07:20:37
【问题描述】:

我正在尝试使用delayed_job 通过 xml 更新远程数据库

在我的 lib 文件夹中,我放置了一个文件,其中包含一个应该使用 template.xml.builder 执行 render_to_text 的类,但我得到了:

undefined method `render_to_string' for #<SyncJob:0x7faf4e6c0480>...

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails templating


    【解决方案1】:

    导轨 5

    render_to_string 和其他现在可用作控制器上的类方法。因此,您可以使用您喜欢的任何控制器执行以下操作:ApplicationController.render_to_string

    我特别需要根据对象的类为模板分配一个动态实例变量,所以我的示例如下所示:

    ApplicationController.render_to_string(
      assigns: { :"#{lowercase_class}" => document_object },
      inline: '' # or whatever templates you want to use
    )
    

    制作 Rails 公关的开发人员的精彩博文:https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions

    【讨论】:

      【解决方案2】:

      我在使用未定义的辅助方法时遇到了问题,然后我使用了ApplicationController

      ApplicationController.new.render_to_string
      

      【讨论】:

      • 这里也一样。你有没有修复过未定义的助手?
      • 在我的情况下,我在调用 AplicationController 时忘记了命名空间。我试试:Usr::ApplicationController.new.render_to_string 它有效。
      【解决方案3】:
      ac = ActionController::Base.new()
      ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})
      

      【讨论】:

      • 如果您尝试将它与实例变量一起使用,请像这样:locals =&gt; {:@instance_variable =&gt; value}
      • 我收到 Missing template 错误,似乎没有找到那个部分,我已经检查了很多次拼写。还是什么都没有..请帮忙
      • 您将收到“缺少模板”错误,因为 ActionController::Base 将在 action_controller/base 路径中搜索。委托给另一个控制器。无论如何,它通常都会继承ActionController::Base
      【解决方案4】:

      您可以将您的 template.xml.builder 转换为部分 (_template.xml.builder),然后通过实例化 ActionView::Base 并调用 render 来渲染它

      av = ActionView::Base.new(Rails::Configuration.new.view_path)
      av.extend ApplicationController.master_helper_module
      xml = av.render :partial => 'something/template'
      

      我还没有尝试使用 xml,但它适用于 html 部分。

      【讨论】:

      • 我得到:Rails::Configuration:Module 的未定义方法 `new'
      【解决方案5】:

      render_to_stringActionController::Base 中定义。由于类/模块是在 Rails 控制器范围之外定义的,因此该功能不可用。

      您将不得不手动渲染文件。我不知道您在模板中使用什么(ERB、Haml 等)。但是您将需要加载模板并自己解析它。

      所以如果是 ERB,是这样的:

      require 'erb'
      
      x = 42
      template = ERB.new <<-EOF
        The value of x is: <%= x %>
      EOF
      puts template.result(binding)
      

      您必须打开模板文件并将内容发送到ERB.new,但您需要做一个练习。这是 ERB 的docs

      这就是一般的想法。

      【讨论】:

        猜你喜欢
        • 2019-11-09
        • 2018-05-23
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 2017-08-25
        • 2015-09-03
        相关资源
        最近更新 更多