How to Pass Variables to ERB Partial Views With Ruby on Rails
How to Pass Variables to Partial Views
Here's how to pass variables around in your Ruby on Rails partial views.
First, we need to render our partial view inside an existing ERB view. That will look something like this:
<%= render partial: "footer" %>
# Or the shorthand version which can omit the "partial" key
<%= render "footer" %>
Next we need to pass the variables to the partial by adding a hash to this render call.
<%= render partial: "footer" locals: {darkmode: false}%>
# The shorthand version may also omit the "locals" key
<%= render "footer", darkmode: false %>
Using Variables in Partial Views
Next, we just need to read this variable from inside out partial view. If we navigate to out partial we can access or variables as if they were passed directly from a controller.
# In our footer partial
<div>
<%= "Darkmode is enabled" if darkmode %>
<div>
Tips & Tricks to Prevent Errors
The above implementation is short and sweet, but very prone to errors.
For example, you'll get a nasty error if you forget to pass the darkmode
variable when you render this partial.
undefined local variable or method `darkmode' for #<#<Class:0x00007fc2979f6a58>:0x00007fc2979feb68>
Instead of forcing yourself to declare this variable every time you render the view, it's much safer to add an extra condition inside your partial to make sure the variable is defined.
That should look something like this:
# In our footer partial
<div>
<%= "Darkmode is enabled" if defined?(darkmode) && darkmode %>
<div>
This makes sure to only call darkmode
if it's defined. Otherwise, we'll treat it as a false condition.
I hope this was helpful, it definitely tripped me up today! ✌️