I'm primarily a LAMP developer that is slowly making the switch to ruby development. In PHP, I can split the page into segments (to maximise code re-use) using separate PHP files for each section. An example of this being wordpress, where you have a separate header / sidebar / content file etc.
Is this possible using Ruby on Rails? Would it be the equivalent of embedding a controller / view into another view? So far i'm a bit stumped on the way anything would be embedded because it seems there is a controller that has a route for a view, so i'm unsure as to which bit you would try include.
What you are looking for are called partials
. You can create a partial, such as a sidebar or a footer, then render it into a template.
The official Rails guide contains some information about using partials .
Essentially, you create a file name prefixed by an underscore such as posts/_form.html.erb
and you render it into the view
<%= render partial: "form" %>
You can also specify an absolute path from the views
folder
<%= render partial: "/posts/form" %>
The same naming conventions of the template (eg the format suffixes) apply.
Here's how I implemented sidebar using partials. Hope this will answers the most part of your question.
First, edit application_controller.rb to pass variables to layout view. Use before_action
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_page
def set_page
@categories = Category.all
end
end
next, edit layout view( application.html.erb )
<body>
<div class="container">
<div class="col-md-10">
<%= yield %>
</div>
<div class="col-md-2">
<%= render partial: 'categories/sidebar' %>
</div>
</div>
</body>
then create partial. You can directory access controller variables from the partial.
/views/categories/_sidebar.html.erb
<h3>Categories</h3>
<div class="row">
<br>
<% @categories.each do |category| %>
<h5 class="media-heading">
<%= link_to category.name, category %>
</h5>
<% end %>
</div>
For page screenshot and more detail, checkout my post .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.