DEV Community

Cover image for How to Pass Variables to ERB Partial Views With Ruby on Rails
Nicholas Dill
Nicholas Dill

Posted on • Originally published at testsuite.io

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 view. That will look something like this:

<%= render partial: "footer" %>

# Or the shorthand version which can omit the "partial" key
<%= render "footer" %>
Enter fullscreen mode Exit fullscreen mode

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 %>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

The defined? method checks if darkmode is defined before calling it. If it's not, we treat it as false.

I hope this was helpful, it definitely tripped me up today! ✌️

Top comments (0)