使用 content_for 确定命名 yield 的正确用法
Determining the correct usage of named yield with content_for
我有很多用于几种不同形式的共享代码,并且正在尝试使用命名的 yield。我希望 _nav.html.haml 使用 content_for 块中定义的每个页面的字段呈现表单。
示例视图:
- content_for :form_fields do
= f.text_field :name
= f.text_field :number
= render :layout => 'projects/shared/nav', locals: {:url => projects_path, :form => @form}
_nav 的内容:
= form_for(form, url: url, layout: :horizontal) do |f|
= f.alert_message "Please fix the errors below before saving this page."
= yield :form_fields
我在示例视图中收到以下错误:
undefined local variable or method `f'
您没有将表单对象传递给 content_for。这就是它显示错误的原因。
不幸的是,除了名称和块之外,您不能将任何参数传递给 content_for。
=> yield(:block_name, form_object)
ArgumentError: wrong number of arguments (2 for 0..1)
from /test/.rvm/gems/ruby-2.1.5/gems/actionpack-4.0.2/lib/action_view/context.rb:31:in `_layout_for'
呈现 content_for 视图的方法仅采用块的名称。在这里检查。
http://www.rubydoc.info/docs/rails/4.1.7/ActionView/Context:_layout_for
你不应该在这里使用 content_for。这里的正确解是"Partials"
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
在难以将表单传递到 content_for 块之后,我最终删除了 content_for 并重新安排我的代码,如下所示:
= render :layout => 'projects/shared/nav', locals: {:url => projects_path, :form => @form} do
= @f.text_field :name
= @f.text_field :number
产量是这样的:
= form_for(form, url: url, layout: :horizontal) do |f|
- @f = f
= f.alert_message "Please fix the errors below before saving this page."
= yield
感觉有点乱,但我想不出另一种方法来传递表单,按预期工作。
我有很多用于几种不同形式的共享代码,并且正在尝试使用命名的 yield。我希望 _nav.html.haml 使用 content_for 块中定义的每个页面的字段呈现表单。
示例视图:
- content_for :form_fields do
= f.text_field :name
= f.text_field :number
= render :layout => 'projects/shared/nav', locals: {:url => projects_path, :form => @form}
_nav 的内容:
= form_for(form, url: url, layout: :horizontal) do |f|
= f.alert_message "Please fix the errors below before saving this page."
= yield :form_fields
我在示例视图中收到以下错误:
undefined local variable or method `f'
您没有将表单对象传递给 content_for。这就是它显示错误的原因。
不幸的是,除了名称和块之外,您不能将任何参数传递给 content_for。
=> yield(:block_name, form_object)
ArgumentError: wrong number of arguments (2 for 0..1)
from /test/.rvm/gems/ruby-2.1.5/gems/actionpack-4.0.2/lib/action_view/context.rb:31:in `_layout_for'
呈现 content_for 视图的方法仅采用块的名称。在这里检查。 http://www.rubydoc.info/docs/rails/4.1.7/ActionView/Context:_layout_for
你不应该在这里使用 content_for。这里的正确解是"Partials"
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
在难以将表单传递到 content_for 块之后,我最终删除了 content_for 并重新安排我的代码,如下所示:
= render :layout => 'projects/shared/nav', locals: {:url => projects_path, :form => @form} do
= @f.text_field :name
= @f.text_field :number
产量是这样的:
= form_for(form, url: url, layout: :horizontal) do |f|
- @f = f
= f.alert_message "Please fix the errors below before saving this page."
= yield
感觉有点乱,但我想不出另一种方法来传递表单,按预期工作。