21 February 2017

Ruby on Rails | Partials

If you have exactly or almost exactly the same code in different places, you can make one generic code of them and use it as a template using partials.

Examples

  • In views folder, you might have the same code for a form in  new.html.erb and edit.html.erb. You can create another file named _form.html.erb and put all the same lines of code in it. In the original place, you can replace the code with <%= render 'file_path' %> please keep in mind that the path should begin with folder name where the file is located.
  • In your partial template, you can also declare variables and you can assign the value of the variable in the target page like this <%= render 'file_path' , variableName: value %>
  • Now and then you will have the situation where the codes are exactly the same except one or two lines. Fortunately rails give us method to handle this. e.g. you want to have different label for a button; on the new page you want it to be labeled "create" and on the edit page you want it to be labeled "update". Simply modify your code into this: <%= f.submit(@user.new_record? ? "sign up" : "update your account" %>

No comments:

Post a Comment