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
    <%= "Darkmode is enabled" if darkmode %>

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
    <%= "Darkmode is enabled" if defined?(darkmode) && darkmode %>

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! ✌️

Level up faster
Recommended Books
Check out my list.
One on Ones: 101
Leveraging Other People's Experience
Hey, I'm Nicholas Dill.

I share everything I know about web development and SEO.

My agency is also offering free site audits for a limited time. Take me up on it while you can!

Related Articles
More like this
How to Render Plain Text Templates in Ruby on Rails
Prevent an Infinite Loop When Using after_save in Rails
How to Fix "Address already in use – bind(2) for “” port 3000 (Errno::EADDRINUSE)"
Best Software Development Blogs -