【问题标题】:How can I pass form variable to footer?如何将表单变量传递给页脚?
【发布时间】:2018-02-18 05:15:49
【问题描述】:

我想将表单的 = f.submit 部分放在页脚部分中,但出现错误:

响应中的名称错误#new

#<#Class<Class:0x00007fcd80439d10>:0x00007fcd804314d0> 的未定义局部变量或方法“f”

您会建议我在下面的代码示例中进行哪些更改?

app/views/layouts/application.html.haml

%body
  %main
    = yield
  %footer
    = render partial: 'layouts/footer', locals: { f: f } # <-- this line errors

app/views/responses/new.html.haml

= form_for @response do |f|
  = f.text_field :answer

app/views/layouts/_footer.html.haml

= f.submit

【问题讨论】:

  • 你为什么不改用submit_tag 呢?它会完成同样的事情
  • 另外,如果您将提交按钮放在表单标签之外,那么它实际上不会提交表单。那么,您将需要一些 JS 来为您提交表单。请参阅下面的答案。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

如果你想分享这样的元素,你可以使用content_foryield,像这样:

# _footer.haml
= yield :footer_content

然后在你的模板文件中:

# new.haml
= form_for @object, id: 'form1' do |f|
  # form elements goes here

= content_for :footer_content do 
  %button{:onclick => "document.getElementById('form1').submit()"}

由于按钮位于表单之外,因此您需要添加该自定义 JS 才能正确提交表单。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2010-12-13
    • 2012-01-31
    相关资源
    最近更新 更多