Skip to content

color_contrast

The color_to_rgb filter is designed to convert color values from Hexadecimal (Hex) or HSL (Hue, Saturation, Lightness) format to RGB (Red, Green, Blue) format.

Functionality

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

Syntax

    {{ input_color | color_to_rgb }}

Arguments

The color_to_rgb filter does not require any arguments.

Code Samples

Example 1: Converting from Hex to RGB

    {{ "#FF0000" | color_to_rgb }}  
    {{ "#F00" | color_to_rgb }}
Output
     rgb(255, 0, 0)
     rgb(255, 0, 0)

Example 2: Converting from HSL to RGB

    {{ "hsl(120, 50%, 25%)" | color_to_rgb }}  
    {{ "hsla(240, 100%, 50%, 0.5)" | color_to_rgb }}
Output
    rgb(64, 128, 64)
    rgba(0, 0, 255, 0.5)

Outliers and Special Cases

  • Invalid Input: If the input string is not a valid Hex or HSL 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 HSLA to RGBA.

Key Points

  • The color_to_rgb filter is primarily useful when you need to work with colors in a consistent format, such as when manipulating colors in JavaScript or CSS.
  • It allows you to easily convert colors between different representations.
  • Ensure that the input string is a valid Hex or HSL color to avoid errors.