Search code examples
rubyhaml

How to pass a hash object to a HAML tag


Please consider this example:

- user_links_params = _user_link_params(current_user)

%a{ :'data-msgstore-path' => user_links_params[:'data-msgstore-path'],
  :'data-user_id' => user_links_params[:'data-user_id'],
  :class => user_links_params[:class],
}
  / too many html tags and stuff to fit in a simple link_to

I would be nice to fit all this in a simple statement like the following:

%a[_user_link_params(current_user)]
  / too many html tags and stuff to fit in a simple link_to

Solution

  • Yes, it's possible, and you were close:

    %a{_user_link_params(current_user)}
    

    From the HAML reference:

    For example, if you defined

    def hash1
      {:bread => 'white', :filling => 'peanut butter and jelly'}
    end
    
    def hash2
      {:bread => 'whole wheat'}
    end
    

    then %sandwich{hash1, hash2, :delicious => true}/ would compile to:

    <sandwich bread='whole wheat' delicious='true' filling='peanut butter and jelly' />