渲染和渲染部分与产量之间的差异

50 ruby-on-rails ruby-on-rails-3.2

我已经从Rails指南中读到了它,看过Micheal Hartel的书,现在从Rails View书中读到它,但我仍然感到困惑:(

有一个_footer.html.erb 文件,所以它是一个"部分",并在其编写的代码中:

<%=render 'layouts/footer' %>
Run Code Online (Sandbox Code Playgroud)

所以我的理解是,当它看到这个时,去并在这里插入页脚文件的HTML.好的...现在几页后它说:

<%= render partial: 'activitiy_items/recent' %>
Run Code Online (Sandbox Code Playgroud)

那么为什么这次我们在这里有"部分"这个词,但我们在前一个没有它?

还有我看到的其他地方 <%= yield :sidebar %>

那么这yield也在它的位置插入HTML?那不是render在做什么?

我希望如果另一个程序员而不是书籍向我解释这个可能我这次得到它:)

MrY*_*iji 105

render & render partial:

  • render 'some_view'是一个简写render partial: 'some_view'.
  • render file: 'view'将查找文件view.html.erb而不是_view.html.erb(.erb或您使用的任何其他渲染器)
  • render不会接受部分的其他局部变量,您需要使用render partial:如下:

    render partial: 'some/path/to/my/partial', locals: { custom_var: 'Hello' }
    
    Run Code Online (Sandbox Code Playgroud)

(http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables)

yield & content_for

  • yield通常用于布局.它告诉Rails将该块的内容放在布局中的那个位置.
  • 当您yield :something关联时content_for :something,您可以传递一个代码块(视图)来显示yield :something放置的位置(参见下面的示例).

关于产量的一个小例子:

在你的布局中:

<html>
<head>
 <%= yield :html_head %>
</head>
<body>
 <div id="sidebar">
   <%= yield :sidebar %>
 </div>
</body>
Run Code Online (Sandbox Code Playgroud)

在你的一个观点中:

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

<% content_for :html_head do %>
  <script type="text/javascript">
    console.log("Hello World!");
  </script>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这将生成以下HTML:

<html>
<head>
  <script type="text/javascript">
    console.log("Hello World!");
  </script>
</head>
<body>
 <div id="sidebar">
   This content will show up in the sidebar section
 </div>
</body>
Run Code Online (Sandbox Code Playgroud)

可能有用的帖子:

文档和指南的链接:

  • 您可以将变量传递给渲染而不使用:partial,至少在Rails 4中.例如.渲染'some/path/to/my/partial',custom_var:'Hello'.请参阅此处的'渲染默认案例':http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html (3认同)