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}" />
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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With