Color field add a class name to body?

I’d like to specify 10 colors the client can use to color the heading on different pages, and to have different background images (so a blue color might have a predominely blue background image). So that the heading and background image are different on different pages.

Can I get the Color field to add a class name to the <body> so that I can select it in the CSS and style the heading and background image?

it would be nice to use the Color field so the client has a visual guide (rather than a select field)

If you use an options array in the config, like described in the field docs (http://getkirby.test/docs/reference/panel/fields/color#options__dynamic-options), you can add a css value there and then fetch the corresponding css class from the array based on the selected color.

So if the user in the Panel selected Color A then there is a way to add this as a class to an element? For example:

<body class="colorA">

Does the Color field store raw color values (rgb, # etc) in the content files? If so, I need a way to convert the color value into a css class name. Is this what the ‘options array’ in the config does? If so, this is well outside my comfort zone. Think I’ll use a select field instead.

Out of interest, if the Color field stores raw color values, how do you use that in a template? Using style?

<h1 style="color: <?= $page->color()->escape('css') ?>;"> ... </h1>

Yes, the color field stores the color values, not any color names.

Yes, that would basically be your “lookup table”, so given a specific color value defined in that array, find the corresponding class value.

Ok… this is probably a dim question, but how do I use this in the template? The ‘lookup table’ converts the stored color value to a label (that could be used as a class name) – but I don’t understand how to add this class to an element? Is it as simple as:

<body class="<?= $page->color_theme() ?>">

=

<body class="colorA">

It works like this:

$colors = option('my.colors'); // returns the color definition array from your config

// Build lookup table (you would do this only once somewhere
$colorMap = array_column(
	$colors,
	'class',
	'hex' 
);

// normalize value
$hex = strtolower($page->color()->value()); // say your color value is #3e3e3e

$class = $colorMap[$hex] ?? null;

echo $class; // result: dull

This assumes a config like this:

	'my' => [
		'colors' => [
			[
				'name'  => 'Color A',
				'hex'   => '#3e3e3e',
				'class' => 'dull'
			],
			[
				'name'  => 'Color B',
				'hex'   => '#aaa',
				'class' => 'bright',
			],
			[
				'name'  => 'Color C',
				'hex'   => '#ddd',
				'class' => 'vibrant'
			]
		]
	]

The code above would be best wrapped in a method, of course.

Learning the basics of PHP helps to solve such problems (or asking an AI).

Hey thanks. I tried ChatGPT but it didn’t seem to know how to do it.