Haml: Append class if condition is true in Haml
.post{:class => ("gray" unless post.published?)}
how to add a class to a conditional in HAML
Call me stupid here, but could you not just put the -unless place.blank? inside a div
.extra_middle
-unless place.blank?
.Whatever else you need
Conditional class in HAML
Try this
%tr{ :class => ("overdue" if ap.overdue?) }
Neat way to conditionally test whether to add a class in HAML template
You can inline the conditional to determine if the class is needed for the %li
%li{ :class => ('current' if section == "pages") }
%a{ :href => "#pages" } Pages
HAML class string with class based on if statement
Use the ternary operator
:
= link_to 'Contact Information',
edit_account_path(:contact_information),
class: "Tab large #{params[:section] == 'contact_information' ? 'active' : ''}"
The second example:
= link_to 'Contact Information',
edit_account_path(:contact_information),
class: current_page?(edit_user_registration_path) ? 'active' : ''
Instance Variable If Else Condition to Add Tag in HAML
You are missing the do
from the line = link_to quote.link
which is throwing the parsing of ending blocks off. You just need to change it to:
= link_to quote.link do
%blockquote
-# ...
HAML conditional tags
If you need to do this logic in different views I think there are two approaches you can follow:
1. Make a partial and render it where you need this. If you need to pass variables use local_assigns
_my_list.html.haml
- if ordered
%ol
- else
%ul
use it
render 'partials/my_list', ordered: ordered
2. Make your own helper
def my_list(ordered)
if ordered
content_tag(:ol, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end else
content_tag(:ul, class: 'my-class') do
# more logic here
# use concat if you need to use more html blocks
end
end
end
use it
= my_list(ordered)
You can keep your ordered variable outside of the view and deal with the whole logic inside the helper.
If you ask yourself what to use, well the first answer from here is pretty good.
Related Topics
How to Wrap Link_To Around Some HTML Ruby Code
Best Practices to Handle Routes For Sti Subclasses in Rails
Ruby/Rails - Change the Timezone of a Time, Without Changing the Value
Why Isn't Current Directory on My Ruby Path
Rails: Skinny Controller Vs. Fat Model, or Should I Make My Controller Anorexic
How to Monitor Delayed_Job With Monit
Converting Ruby Array to Array of Consecutive Pairs
What Are the Benefits of the New Hash Syntax in Ruby 1.9
Undefined Method Raise_In_Transactional_Callbacks=' for Activerecord::Base:Class (Nomethoderror)
Really Cheap Command-Line Option Parsing in Ruby
Why Not Use Shared Activerecord Connections For Rspec + Selenium
Can't Install Pg Gem on Windows
Stop Devise from Clearing Session
Ruby: What Does the Comment "Frozen_String_Literal: True" Do