Skip to content

color_to_hsl

The color_to_hsl filter is designed to convert color values from Hexadecimal (Hex) or RGB (Red, Green, Blue) format to HSL (Hue, Saturation, Lightness) format. HSL is often preferred for its intuitive representation of colors using hue, saturation, and lightness components.

Functionality

  • Color Values: Takes a color value as input, expecting it to be in either Hex or RGB format.
  • Hex Input:
    • Supports both shorthand (#RGB) and longhand (#RRGGBB) Hex color codes.
  • RGB Input:
    • Supports both RGB (rgb(R, G, B)) and RGBA (rgba(R, G, B, A)) formats, where A is the alpha (transparency) value (0 to 1).
  • Conversion: Converts the input color to its equivalent HSL representation.
  • Output: Returns a string representing the color in HSL format.
    • For opaque colors (no transparency), the format is hsl(H, S%, L%).
    • For colors with transparency, the format is hsla(H, S%, L%, A), where A is the alpha value (0 to 1).

Syntax

    {{ input_color | color_to_hsl }}

Arguments

The color_to_hsl filter does not require any arguments.

Code Samples

Example 1: Converting from Hex to HSL

    {{ "#FF0000" | color_to_hsl }}  <br>
    {{ "#F00" | color_to_hsl }}     <br>
Output
    hsl(0, 100%, 50%)
    hsl(0, 100%, 50%)

Example 2: Converting from RGB to HSL

    {{ "rgb(0, 255, 0)" | color_to_hsl }}  <br>
    {{ "rgba(255, 128, 0, 0.8)" | color_to_hsl }}  <br>
Output
    hsl(120, 100%, 50%)
    hsla(30, 100%, 50%, 0.8)

Outliers and Special Cases

  • Invalid Input: If the input string is not a valid Hex or RGB color, the filter will return a nil value or an error message.
  • Non-String Input: If the input is not a string, the filter might attempt to convert it to a string or return an error.
  • Alpha Values: The filter preserves alpha (transparency) values when converting from RGBA to HSLA.

Key Points

  • The color_to_hsl filter is helpful when you prefer working with the HSL color model, which is often considered more intuitive for adjusting colors.
  • It allows you to easily switch between different color representations within your templates.
  • Ensure that the input string is a valid Hex or RGB color to avoid errors.