0

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>
3
  • What do you mean? You are passing the local variable className and also referencing className. Are you sure this is not just a typo or sloppy error? Commented Dec 14, 2016 at 0:23
  • className is not getting into the partial as "classy". I want my div to get the class "classy" Commented Dec 14, 2016 at 0:24
  • It should be <%= className if local_assigns.has_key?(:className) %>. Since className and className? are not the same. local_assigns.has_key?(:className) is a way of safely checking if the local variable is set. Commented Dec 14, 2016 at 0:34

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.