Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove HTML tag attribute in slim when attribute should not be displayed

I would like to remove class attribute when class should not be displayed in Slim.

In ERB, I could use:

<input <%= "class='foo'" if false %> />
<input />

How do I do this in Slim?

I found this, but I feel there must be a more idiomatic solution:

| <input "#{'class=\"foo\"' if false}" />
like image 430
Piioo Avatar asked Mar 14 '13 14:03

Piioo


2 Answers

If the value of an attribute is nil, then the entire attribute will be omitted (actually this is happens for nil or false for most cases, but it looks like the class attribute behaves differently for false and true):

input class=('foo' if condition)

This will output

<input class="foo" />

if condition is true, and

<input />

if condition is false.

like image 199
matt Avatar answered Oct 19 '22 08:10

matt


You can use the splat (*) operator to help define conditional attributes for tags in slim, using hashes containing the attributes to be added.

http://www.rubydoc.info/gems/slim/frames#Splat_attributes__

The splat operator will expand a hash into a set of attributes to be added to the tag. If the hash is empty, no attributes will be added.

For example,

- admin_classes = @User.admin? ? {class: "foo"} : {}
input *admin_classes

if @User.admin? == true, it should render

<input class="foo">

else if @User.admin? == false, it should render

<input>   

For attributes like "class" or other attributes that have attribute merging turned on, you can also do something like this:

- admin_classes = @User.admin? ? {class: ["foo","bar"]} : {}
input *admin_classes class="biz"

if @User.admin? == true, it should render

<input class="foo bar biz">

else if @User.admin? == false, it should render

<input class="biz">   
like image 29
Greg Becker Avatar answered Oct 19 '22 07:10

Greg Becker