color_extract¶
The color_extract filter allows you to extract specific components (red, green, blue, alpha, hue, saturation, or lightness) from a color value provided in Hex, RGB, or HSL format. This is particularly helpful for dynamic styling or conditional logic based on color attributes.
Functionality
- Color Values: Takes a color value as input, expecting it to be in either Hex, RGB, or HSL format.
- Hex Input:
- Supports both shorthand (
#RGB) and longhand (#RRGGBB) Hex color codes.
- Supports both shorthand (
- 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 (
- Component Extraction: Extracts the value of the specified color component.
- Output: Returns a string representation of the extracted component's value.
- For RGB components (red, green, blue), the output is an integer between 0 and 255.
- For alpha, the output is a decimal number between 0 and 1.
- For HSL components (hue, saturation, lightness), the output is an integer:
- Hue is an integer between 0 and 360.
- Saturation and lightness are integers between 0 and 100 (representing percentages).
Syntax
Arguments- component_name: A string specifying the component to extract. The following values are supported:
"red": Extracts the red component from the color."green": Extracts the green component from the color."blue": Extracts the blue component from the color."alpha": Extracts the alpha (transparency) component from the color."hue": Extracts the hue component from the color."saturation": Extracts the saturation component from the color."lightness": Extracts the lightness component from the color.
Code Samples Sure, here are the rewritten examples:
Example 1: Extracting RGB Components
OutputExample 2: Extracting the Alpha Component
OutputExample 3: Extracting HSL Components
{{ "hsl(120, 50%, 25%)" | color_extract: "hue" }} <br>
{{ "hsla(240, 100%, 50%, 0.5)" | color_extract: "lightness" }} <br>
Outliers and Special Cases¶
- Invalid Input: If the input string is not a valid Hex, RGB, or HSL color, the filter will likely 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.
- Invalid Component Name: If an unsupported
component_nameis provided, the filter will likely return anilvalue or an error.
Key Points¶
- The
color_extractfilter is a versatile tool for working with color components individually. - It can be used for creating dynamic styles based on color values or for implementing conditional logic related to colors.
- Be sure to provide valid color input and component names to ensure correct behavior.