New in Symfony 5.2: True colors in the console
September 22, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
-----
NOTE from administrators: we deleted the code example included in this comment because blog comments are not prepared to include source code. Here's a public Gist with the original code:
https://gist.github.com/javiereguiluz/4c9075f87cfe8db094c676ded824056d