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).
- Supports both RGB (
- HSL Input:
- Supports both HSL (
hsl(H, S%, L%)) and HSLA (hsla(H, S%, L%, A)) formats.
- Supports both HSL (
- Conversion: Converts the input color to its equivalent Hex representation.
- Output: Returns a string representing the color in Hex format (
#RRGGBBfor opaque colors or#RRGGBBAAfor colors with alpha).
Syntax
Arguments
The color_to_hex filter does not require any arguments.
Code Samples
Example 1: Converting from RGB to Hex
OutputExample 2: Converting from HSL to Hex
OutputOutliers and Special Cases¶
- Invalid Input: If the input string is not a valid RGB or HSL color, the filter will return a
nilvalue 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_hexfilter 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.