Skip to content

color_to_hex

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

Functionality

  • Color Values: Takes a color value as input, expecting it to be in either RGB or HSL format.
  • 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).
  • HSL Input:
    • Supports both HSL (hsl(H, S%, L%)) and HSLA (hsla(H, S%, L%, A)) formats.
  • Conversion: Converts the input color to its equivalent Hex representation.
  • Output: Returns a string representing the color in Hex format (#RRGGBB for opaque colors or #RRGGBBAA for colors with alpha).

Syntax

   {{ input_color | color_to_hex }}

Arguments

The color_to_hex filter does not require any arguments.

Code Samples

Example 1: Converting from RGB to Hex

    {{ "rgb(255, 0, 0)" | color_to_hex }}  <br>
    {{ "rgba(0, 128, 255, 0.8)" | color_to_hex }}  <br>
Output
    #FF0000
    #0080FFCC

Example 2: Converting from HSL to Hex

    {{ "hsl(120, 50%, 25%)" | color_to_hex }}  <br>
    {{ "hsla(300, 75%, 80%, 0.2)" | color_to_hex }}  <br>
Output
    #408040
    #F2E5D933

Outliers and Special Cases

  • Invalid Input: If the input string is not a valid RGB 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 values (transparency) when converting from RGBA or HSLA inputs.

Key Points

  • The color_to_hex filter is commonly used when you need to represent colors in a compact, web-friendly format.
  • It allows you to easily switch between different color representations within your templates.
  • Ensure that the input string is a valid RGB or HSL color to avoid errors.