Partials
Location
The view partial files are located in the app/views/partials
directory.
Convention
Despite views, partials and layouts having separate directories, it may sometimes get confusing having to deal with all three when working on your application.
Following Rails convention, file names for partials should ideally begin with an underscore.
Typical example pattern
Suppose we have a portfolio website where projects are displayed on the projects
page.
The projects
page will be loaded with a layout, and so is not a full view itself. One typical approach would be:
But ideally view files should be clean, easy to read and most importantly, isolated from the logic.
Typically logic should be restricted to controllers, models and helpers (as well as partials where appropriate).
To clean this view file up, we will need a new partial containing all of the erb
code necessary for displaying projects (Simply copying the ruby
code part from the above view file).
We can then clean up our projects.erb
file by calling the partial
function (which is already defined in Eucalypt) in the view:
If you have variables that need to be used in the partial, simply pass them as keyword arguments in the partial
function:
The variables count
and top_lang
will then be usable in the partial's ERB file. They are treated as local variables, so just access them by their name.
Last updated