How to save css code to css file by panel?

I want to define some field in the panel and save it to a css file.
This way I can implement some adjustments to the overall style by defining some CSS variables.
reference: Using CSS custom properties (variables) - CSS: Cascading Style Sheets | MDN


Like this.

I added the following code to site/config/config.php.
primary_color is field name in site.yml.

'hooks' => [
    'site.update:after' => function ($site) {
      $css = $site->primary_color()->value();
      F::write(kirby()->root('assets') . '/css/custom.css', $css);
    }
  ],

But after I save it prompts:

The form could not be saved
Exception: Error
Call to a member function primary_color() on null

I refer to this post
change $site to $newSite.
looks very good.

  'hooks' => [
    'site.update:after' => function ($newSite) {
      $css =  ':root {
  --primary-color: ' . $newSite->primaryColor()->value() . ';
  --secondry-color: ' . $newSite->secondryColor()->value() . ';
}';
      F::write(kirby()->root('assets') . '/css/custom.css', $css);
    }
  ],
1 Like