【问题标题】:What is the syntax for named yield with both names and parameters in ruby/rails?在 ruby​​/rails 中同时具有名称和参数的命名 yield 的语法是什么?
【发布时间】:2013-11-06 06:16:50
【问题描述】:

可以在 rails 的视图中使用 yield:name

= yield :some_place

然后使用 then 使用 content_for :some_place do ... 仅在放置 yield :some_place 的位置插入代码块 (http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method)。

ruby 还允许在 yiled (http://www.tutorialspoint.com/ruby/ruby_blocks.htm) 中传递参数:

def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}

但我没有发现任何关于在 Rails 视图中使用 yield/content_for 的名称和参数

= yield :some_place, 5, 6

...

= content_for :some_place do |a,b|  
  h3 = "Yield provided parameters: #{a} and #{b}"

有可能吗? yield 语句和传递块的官方 rails 或 ruby​​ 语法在哪里? 我听说了一些关于 Proc.new() 的消息,这可能与问题有关。

【问题讨论】:

    标签: ruby-on-rails ruby yield


    【解决方案1】:

    content_for(:name) 首先进行评估,并存储一段 HTML 以供以后使用。 yield(:name) 仅获取此内容。因此,您不能将参数传递给已调用且不会再次调用的方法。

    您可能只需要剪切部分 HTML.erb 文件,然后从目标位置呈现它。渲染将命名参数作为哈希。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2017-05-29
      • 2019-04-09
      相关资源
      最近更新 更多