Color Fields

You are viewing documentation for an unreleased version of Craft CMS. Please be aware that some pages, screenshots, and technical reference may still reflect older versions.

Color fields give you a hexadecimal color input with a preview of the current color, and on browsers that support <input type="color">, clicking on the preview will open the browser’s color picker.

# Development

Calling a Color field in your templates will return a craft\fields\data\ColorData (opens new window) object, or null if no color was selected.

By default, the bare field handle will return a hexadecimal representation of that color:

{% if entry.myFieldHandle %}
  <style type="text/css">
    .content a {
      color: {{ entry.myFieldHandle }};
    }
    .content b {
      {# same thing #}
      color: {{ entry.myFieldHandle.getHex() }};
    }
  </style>
{% endif %}

Here’s an impractical example illustrating each craft\fields\data\ColorData (opens new window) method:

{% if entry.myFieldHandle %}
  {{ entry.myFieldHandle }}                 {# output: #e5422b #}
  {{ entry.myFieldHandle.getHex() }}        {# output: #e5422b #}
  {{ entry.myFieldHandle.getRgb() }}        {# output: rgb(229,66,43) #}
  {{ entry.myFieldHandle.getHsl() }}        {# output: hsl(7,81%,90%) #}
  {{ entry.myFieldHandle.getLuma() }}       {# output: 0.38820862745098 #}
  {{ entry.myFieldHandle.getHue() }}        {# output: 7 #}
  {{ entry.myFieldHandle.getLightness() }}  {# output: 90 #}
  {{ entry.myFieldHandle.getSaturation() }} {# output: 81 #}
  {{ entry.myFieldHandle.getRed() }}        {# output: 229 #}
  {{ entry.myFieldHandle.getGreen() }}      {# output: 66 #}
  {{ entry.myFieldHandle.getBlue() }}       {# output: 43 #}
{% endif %}

The example omits the getL(), getS(), getR(), getG(), and getB() methods, which are abbreviated forms of getLuma(), getSaturation(), getRed(), getGreen(), and getBlue() respectively.