Search code examples
htmlruby-on-railsrubyruby-on-rails-4erb

Inject local variables into rails partial


I want my partial below to get the classy class from it being injected through locals, but I keep getting undefined method for classy.

//view

<%= render layout: "layouts/partial", locals: {className: "classy"} do %>
...
<% end>

//partial

<div class="regular-div <%=className if className?%>"></div>

Solution

  • To check if a local variable is set use local_assigns.has_key?(:some_key) or local_assigns[:some_key] to safely access the local variable.

    A nifty way of handling the common task of building a list of classes is:

    module ApplicationHelper
      # Takes an array or list of classes and returns a string
      # Example:
      #  class_list('a', 'b', nil, 'c')
      #  => "a b"
      #  class_list(['a', 'b', nil, 'c'])
      #  => "a b c"
      def class_list(*classes)
        [*classes].flatten.compact.join(' ') 
      end
    end
    

    Then you can do:

    <div class="<%= class_list('regular-div', local_assigns[:className]) %>"></div>