Ruby-on-rails Rails:关于产量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7848020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:12:53  来源:igfitidea点击:

Rails: about yield

ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

提问by Mellon

I saw some code in a Rails v2.3app.

我在Rails v2.3应用程序中看到了一些代码。

In layout/car_general.html.erb(this view is called by a method in cars_controller) , I saw the code:

layout/car_general.html.erb(这个视图被cars_controller中的一个方法调用)中,看到了代码:

<body>
    <%= yield %>

    <%= javascript_include_tag 'jquery-1.4.2.min' %>

    <% javascript_tag do %>
      <%= yield :jstemplates %>
          var some_car = new Object;
      <%= yield :some_car %>
    <% end -%>
</body>

Two questions to ask:

问两个问题:

  1. Where can I find the yield content of the first <%=yield%> under <body>.
  2. Is it a rails specific way to include js code in a view by using <%= yield :jstemplates %>and what about <%= yield :some_car %>, is it point to a view or just to show the value of some_car?
  1. 在哪里可以找到第一个 <%=yield%> 下的产量含量<body>
  2. 它是通过使用将 js 代码包含在视图中的特定于 rails 的方式 <%= yield :jstemplates %><%= yield :some_car %>,它是指向视图还是仅显示 的值some_car

回答by Peter Brown

Without any arguments, yield will render the template of the current controller/action. So if you're on the cars/showpage, it will render views/cars/show.html.erb.

没有任何参数,yield 将呈现当前控制器/动作的模板。因此,如果您在cars/show页面上,它将呈现views/cars/show.html.erb.

When you pass yield an argument, it lets you define content in your templates that you want to be rendered outside of that template. For example, if your cars/showpage has a specific html snippet that you want to render in the footer, you could add the following to your show template and the car_generallayout:

当您传递 yield 参数时,它允许您在模板中定义要在该模板之外呈现的内容。例如,如果您的cars/show页面具有要在页脚中呈现的特定 html 片段,您可以将以下内容添加到您的展示模板和car_general布局中:

show.html.erb:

show.html.erb:

<% content_for :footer do %>
  This content will show up in the footer section
<% end %>

layouts/car_general.html.erb

布局/car_general.html.erb

<%= yield :footer %>

The Rails Guide has a good section on using yield and content_for: http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield

Rails 指南有一个关于使用 yield 和 content_for 的很好的部分:http: //guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield

The API documentation for content_foris helpful too and has some other examples to follow. Note that it's for Rails 3.1.1 , but this functionality has not changed much since 2.3, if at all and should still apply for 3.0.x and 3.1.x.

的 API 文档content_for也很有帮助,还有一些其他示例可供参考。请注意,它适用于 Rails 3.1.1 ,但此功能自 2.3 以来没有太大变化,如果有的话,仍然适用于 3.0.x 和 3.1.x。