Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

ruby on rails - Difference between Render and Render Partial and Yield

I have read it from the Rails guides, Have looked at Micheal Hartel book and now reading it from Rails View book but still I get confused :(

There is a _footer.html.erb file so it is a "partial" and in the code it has written:

<%=render 'layouts/footer' %>

so my understanding is that when it sees this, goes and insert the HTML for footer file in here. Ok... Now a few pages later it is saying:

<%= render partial: 'activitiy_items/recent' %>

so WHY this time we have the word "partial" in here but we didn't have it in the previous one?

And there somewhere else I see <%= yield :sidebar %>

So this yield also insert HTML in its place? Well wasn't it what render was doing?

I was hoping if another programmer instead of books explains this to me maybe I get it this time:)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

render & render partial:

  • render 'some_view' is a shorthand for render partial: 'some_view'.
  • render file: 'view' will look for a file view.html.erb and NOT _view.html.erb (.erb or any other renderer you use)
  • render will not accept additional local variables for the partial, you need to use render partial: as following for that:

    render partial: 'some/path/to/my/partial', locals: { custom_var: 'Hello' }
    

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

yield & content_for

  • yield is typically used in layouts. It tells Rails to put the content for this block at that place in the layout.
  • When you do yield :something associated with content_for :something, you can pass a block of code (view) to display where the yield :something is placed (see example below).

A small example about yield:

In your layout:

<html>
<head>
 <%= yield :html_head %>
</head>
<body>
 <div id="sidebar">
   <%= yield :sidebar %>
 </div>
</body>

In one of your view:

<% 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 %>

This will produce the following 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>

Posts that might help:

Links to documentation & guides:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...