【问题标题】:How to render template to a variable in Padrino?如何将模板渲染到 Padrino 中的变量?
【发布时间】:2014-10-03 15:21:13
【问题描述】:

我正在尝试在 Padrino 中实现一个嵌套表单,我可以在其中使用界面中的 Add whatever 按钮添加子对象的多个实例。

在 Rails 中,一种方法是创建一个帮助程序,每次单击 Add whatever 按钮时生成嵌套字段:

def link_to_add_fields( text, f, association, target )

  new_object    = f.object.class.reflect_on_association(association).klass.new
  template_path = "#{association}/fields" 

  template = f.fields_for(association, new_object) do |builder|
    render(template_path, :f => builder)
  end

  link_to text, "#", onclick: "add_#{association}_fields(this, \"#{escape_javascript(template)}\", \"#{target}\")"

end

但是,当我尝试在 Padrino 中执行此操作时,f.fields_for (...) 块不会渲染到 template 变量,而是显示在布局中。

我试图在 Padrino 框架中找到类似 render_to_string 或类似的东西。

有人知道如何解决这个问题吗?谢谢

【问题讨论】:

    标签: ruby-on-rails nested-forms padrino form-helpers


    【解决方案1】:

    让你失望的不是render,而是fields_for。它错误地检测到它是从您的 erb 模板调用的并连接到它。

    本质上是正确的,因为您从 erb 调用了 link_to_add_fields,但当时没有检测方法来猜测从 erb 到 ruby​​ 并返回的这种双重潜水。

    它可以被认为是一个错误,您可以在这里创建一个问题 https://github.com/padrino/padrino-framework 并提供一个带有锁定 Gemfile 的最小失败项目。

    作为一种解决方案,我建议您手动将渲染引擎切换为 ruby​​ 并返回如下:

      def my_rendery_helper
         @current_engine, engine_was = nil, @current_engine
         template = fields_for(:moo) do |builder|
           render('moo')
         end
         @current_engine = engine_was
         template # now contains a SafeBuffer string
         'result'
      end
    

    @current_engine是一个类变量,用于内部检测渲染引擎。

    【讨论】:

    • 非常感谢您的回答。我将在 Padrino 的 Github 存储库上打开一个问题并与大家讨论!
    猜你喜欢
    • 2015-04-17
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2017-11-27
    相关资源
    最近更新 更多