Ruby on Rails - partials in ruby n rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from our templates to separate files and also reuse them throughout your templates.
To create a partial, create a new file that begins with an underscore:
To render a partial as part of a view, use the render method within the view:
- Note, the underscore is left out when rendering
- A partial has to be rendered using its path if located in a different folder
To pass a variable into the partial as a local variable, use this notation:
Partials are also useful when we need to reuse exactly the same code (DRY philosophy).
Example
To reuse code, create a partial named _html_header.html.erb, enter our code to be reused, and render the partial whenever needed by:
Object Partials
- Objects that respond to to_partial_path can also be rendered, as in <%= render @post %>. By default, for ActiveRecord models, this will be something like posts/post, so by actually rendering @post, the file views/posts/_post.html.erb will be rendered.
- A local named post will be automatically assigned. In the end, <%= render @post %> is a short hand for <%= render 'posts/post', post: @post %>.
- Collections of objects that respond to to_partial_path can also be provided, such as <%= render @posts %>. Each item will be rendered consecutively.
Global Partials
To create a global partial that can be used anywhere without referencing its exact path, the partial has to be located in the views/application path. The previous example has been modified below to illustrate this feature.
Example
- This is a path to a global partial app/views/application/_html_header.html.erb:
- To render this global partial anywhere, use <%= render 'html_header' %>