How would I go about adding a simple menu to a Rails Application? (How to use yield :menu)
I want to add a menu to my First Ever Rails Applicat开发者_Go百科ion. Nothing too complicated. I've worked out that I should maybe reference it from application.html.erb, but after that I'm stuck.
Here's what I've got so far (It's not much)
<%= render :partial => "menu" %>
If I'm rendering a partial call "menu" in application.html.erb, where do I put the menu file, and what do I call it? Does it need to go in the controller of the view?
Can I call this partial from whichever layout subfolder I'm in?
Part II. If I want to show different content according to the view I'm in - how do I do this?
<body>
<p>[<%= yield :menu %>]</p>
<%= yield %>
</body>
</html>
I'm just learning Rails, so sorry about the stupid questions. Also, I'm interested in not only a solution, but also an idea of best practices.
In basic terms you are looking for the content_for
helper. You put this inside your views which will then populate named blocks in partials or layouts such as :menu
. You may elect, if you wish, to use partials to actually define the content for the content_for
regions.
In a view:
<% content_for :menu do %>
<ul>
<li> ... </li>
<li> ... </li>
</ul>
<% end %>
or as:
<% content_for :menu do %>
<%= render :partial => "some_menu_content" %>
<% end %>
In the layout or partial:
<div id="menu">
<%= yield :menu%>
</div>
Watch this screencast from the Railscasts series for more information. It's old but still applicable
精彩评论