Skip to content

Instantly share code, notes, and snippets.

@kcurbelo
Created February 18, 2015 18:13
Show Gist options
  • Save kcurbelo/de6a0a9cf35583f6d287 to your computer and use it in GitHub Desktop.
Save kcurbelo/de6a0a9cf35583f6d287 to your computer and use it in GitHub Desktop.
Using partials to make your project DRY.

Partials


This markdown will be covering the basics of partials. Also known as “partial templates”, partials allow you to move the code for rendering a partial piece of a code into a separate file.

These are indicated by an underscore in front of the view file name, for example _form.html.erb

Lets say that we had this example code:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<h1>Sign up!</h1>

<%= form_for @user do |f|%>
    First name: <%= f.text_field :f_name %><br />
    Last last: <%= f.text_field :l_name %><br />
    E-mail: <%= f.text_field :email %><br />
    Password: <%= f.password_field :password %><br />
    Password confirmation: <%= f.password_field :password_confirmation %><br />
    <%=f.submit %>

<% end %>

</body>
</html>

If other information along with this form the page could begin to look a bit busy. We could use a partial to clean it up.

We would make a new partial file in the layouts folder so that way it would be available on multiple pages.

The same html with a partial would look something like:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<h1>Sign up!</h1>

<%= render 'form' %>

</body>
</html>

Notice that when we render the form we use the syntax, render with form (the name of the partial) in ticks.

That is a basic way to make your projects more DRY using partials.


Contributors:

Lauren Powell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment