Blog

Thoughts from my daily grind

Dynamically specify HTML attributes in HAML

Posted by Ziyan Junaideen |Published: 22 May 2021 |Category: Ruby on Rails
Default Upload |

HAML is a popular HTML abstraction markup language used by the Ruby developer community. Usually, the HAML tags and their attributes are static. How eve there are times we need to add logic. Here are some examples:

Using a variable to populate an attribute:

%div.control-group{"class" => @form.styleClass[:name]}
// <div class="control-group inline"></div>

Using a conditional to set an attribute value

%div.control-group{"class" => ('error' if @form.errors[:name].any?)}
// <div class="control-group error"></div>

Using string interpolation to set an attribute value

%div{"class" => "control-group #{'error' if @form.errors[:name].any?}"}
// <div class="control-group error"></div>

Enabling disabling select options based on users permissions (Pundit style):

%select#salesforce-suggestion-picker
  // ...
  %option{"value" => "create_account", "data-sf-type" => "Account", "diasbled" => policy(@form).create_account?}
  %option{"value" => "create_account", "data-sf-type" => "Contact", "diasbled" => policy(@form).create_contact?}
Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments