Open In App

How to append class if condition is true in Haml?

We will be looking at two ways of appending a class to an element depending on some condition’s evaluation. Essentially, the logic behind both of them is the same.

Initial code: First, let’s write some basic HAML code. It will contain a style element in the head section. The style element will contain all the styles defined for the classes. Initially, there’s an anchor element in the body section and it has a class “add-background” to it. The style defined for this class in the style element will give a light grey background to the text of the anchor element.



Method 1: Suppose we have a class named “make-red” to be appended. The style defined for this class in the style element is such that it will turn the color of the text red. This class will only be appended to the already existing “add-background” if some condition evaluates to true.
Let’s take a boolean variable “flag”. The “make-red” class will be appended only if the value of “flag” is true, otherwise not.

Method 2: Using the “unless” conditional check. This type of check ensures that a certain operation is performed as long some condition is not true. So, as demonstrated below, in this case, the class “make-red” will be appended if “flag” is false does not evaluate to true. That is, if “flag” is false, the class won’t be appended or else it will be appended.




Article Tags :