Extending the text block with text color select field

I would like to extend the text block with a select field with which you can determine the text color.
With the Blueprint this works very well - but with the Template / Snippet I am not sure if this is a good solution.
Maybe an experienced Kirby user can take a look at it?


extends: blocks/text
      extends: fields/colors
      label: Text color


if ($block->text_color()->isNotEmpty()):
  $text = $block->text();
  $search = ["<p>"];
  $replace = ["<p class='text-color--" . $block->text_color() . "'>"];
  echo str_replace($search, $replace, $text);
  echo $block->text();

Does this look strange to you or can I do so?
Patrick :wink:

edit: something was replaced twice…

$text = $block->text();
if($block->text_color()->isNotEmpty()) {
  $text = preg_replace('/<p>/', '<p class="text-color--' . $block->text_color() . '">', $text);
echo $text;

Thanks :wink:

I am not sure why you are using preg_replace instead of str_replace and why it doesn’t throw out an exception because of the missing else statement…

An if statement doesn’t (necessarily) need an else statement. In my example above, we first define $text. If the condition is true, $text gets redefined (whereas you set your condition first and inside that condition define $text.

You can also use str_replace instead of preg_replace:

  $text = str_replace('<p>', '<p class="text-color--' . $block->text_color() . '">', $text);

Ah, understood :wink:
Best, Patrick