Fabien Potencier
Contributed by Fabien Potencier in #36802

The Symfony Console component provides a default styling for your command output, but you can also apply custom styles and colors. However, you could only use the eight basic ANSI colors for text and background colors.

In Symfony 5.2 we're improving this feature to support 24-bit colors, also known as "true colors". In total, more than 16 million different colors to make your console commands look gorgeous.

Instead of supporting all the different ways of defining colors (RGB, HSV, HSL, named colors, etc.) we've opted for a pragmatic solution based on hexadecimal colors, which are well-known by developers/designers and easy to get from any design application.

The most straightforward way of using these new hexadecimal colors is via the fg and bg shortcuts in the output contents:

1
2
3
4
5
6
7
8
// using a predefined style
$output->writeln('<info>... contents ...</>');

// custom style using basic colors
$output->writeln('<fg=green;bg=blue>... contents ...</>');

// custom style using true colors
$output->writeln('<fg=#00ff00;bg=#00f>... contents ...</>');

Hexadecimal colors must include the # prefix and they can be 3 or 6 character long only (8-character values which include the alpha channel are not supported). You can also use these colors outside the Console component via the new Color class:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Console\Color;

$color = new Color('#00ff00', '#00f');
echo $color->apply('... contents ...');

// you can mix basic and true colors
$color = new Color('red', '#00f');

// the third optional argument defines the styles
$color = new Color('#000', '#fff', ['underscore', 'reverse']);

If true colors are not supported by the console/terminal, they fall back to the most similar default color.

Published in #Living on the edge