How to use a ruby local variable within a haml template to dynamically adjust a tags attributes

3,041 views
Skip to first unread message

KJoyner

unread,
Dec 14, 2007, 3:55:21 PM12/14/07
to Haml
Within my haml template, I was trying to add a :style => 'display:
none' to a div depending on a ruby local variable being passed into my
haml template.

I am able to do this with the following code but it only works if
there are no other attributes:

.my_class{ hidden ? { :style => 'display: none' } : {} }

However, if I have other attributes such as :id => then I cannot get
it to work. For example,
.my_class{ :id => "my_id", hidden { :style => 'display: none' }}
does not work

I also tried the following but could not get it to work

- class_attributes = { :id => "my_id" }
- if hidden
class_attributes.merge( { :style => 'display: none' })

Thanks for any help,

-- Ken

Nathan Weizenbaum

unread,
Dec 14, 2007, 4:36:53 PM12/14/07
to ha...@googlegroups.com
If you pass an attribute a nil value, it won't render. Thus you can do
something like

.my_class{:id => "my_id", :style => hidden ? 'display: none' : nil}

- Nathan

Jeff Casimir

unread,
Dec 14, 2007, 7:29:31 PM12/14/07
to ha...@googlegroups.com
Nathan's technique would of course work, but I'm always hesitant to put styling into my HTML much less my templates.

What about separating the concerns a little...

In the controller/RJS:

@visibility = hidden ? 'hidden' : visible

in the haml template:

div{:id => "my_id", :class => @visibility}

In the sass file:

.hidden
  :display none

Or, let's say you have many of whatever this thing is....

@visibility["my_id"] = hidden ? 'hidden' : visible

and in the haml

div{:id => "my_id", :class => @visibility["my_id"]}

I could see an argument that this looks like more work, but it is a lot more flexible in the future.  Think, for instance, what if you need a third state?  Visible/Hidden/Highlighted?  Putting a boolean all over your templates will require a lot of replacing.  Assigning a variable in the controller logic can centralize the work.

Just a thought,
Jeff
Reply all
Reply to author
Forward
0 new messages